<?php
declare(strict_types=1);
require_once __DIR__ . '/../src/bootstrap.php';

$uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$base = Auth::basePath();
if ($base !== '' && str_starts_with($uri, $base)) {
    $uri = substr($uri, strlen($base)) ?: '/';
}
$route = rtrim($uri, '/') ?: '/';

if ($route === '/api/health.php' || str_ends_with($route, '/api/health.php')) {
    require __DIR__ . '/api/health.php';
    exit;
}
if ($route === '/api/builds.php' || str_ends_with($route, '/api/builds.php')) {
    require __DIR__ . '/api/builds.php';
    exit;
}
if ($route === '/api/build_trigger.php' || str_ends_with($route, '/api/build_trigger.php')) {
    require __DIR__ . '/api/build_trigger.php';
    exit;
}
if ($route === '/api/build_log.php' || str_ends_with($route, '/api/build_log.php')) {
    require __DIR__ . '/api/build_log.php';
    exit;
}
if ($route === '/api/build_actions.php' || str_ends_with($route, '/api/build_actions.php')) {
    require __DIR__ . '/api/build_actions.php';
    exit;
}
if ($route === '/api/heartbeat.php' || str_ends_with($route, '/api/heartbeat.php')) {
    require __DIR__ . '/api/heartbeat.php';
    exit;
}

if ($route === '/logout') {
    Auth::logout();
    header('Location: ' . $base . '/login');
    exit;
}

if ($route === '/login' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = trim($_POST['username'] ?? '');
    $pass = $_POST['password'] ?? '';
    if (Auth::login($user, $pass)) {
        header('Location: ' . $base . '/');
        exit;
    }
    $loginError = 'Invalid credentials';
    require __DIR__ . '/../views/login.php';
    exit;
}

if ($route === '/login') {
    require __DIR__ . '/../views/login.php';
    exit;
}

Auth::check();

BuildRunner::reconcileRunningBuilds();

$view = $_GET['view'] ?? 'home';

if ($view === 'build' && isset($_GET['id'])) {
    $build = BuildRepository::getById((int) $_GET['id']);
    if (!$build) {
        http_response_code(404);
        echo 'Not found';
        exit;
    }
    if ($build['status'] === 'running' && is_file(BuildRunner::artifactDir((int) $build['id']) . '/android_cast-latest.apk')) {
        BuildRunner::finalizeFromArtifacts((int) $build['id']);
        $build = BuildRepository::getById((int) $_GET['id']);
    }
    $health = BuildRepository::healthSummary();
    $view = 'build';
    $pageTitle = 'Build ' . ($build['build_code'] ?? '');
    require __DIR__ . '/../views/layout.php';
    exit;
}

$view = 'home';
$health = BuildRepository::healthSummary();
$builds = BuildRepository::listRecent(10);
$pageTitle = 'Builder';
require __DIR__ . '/../views/layout.php';
