<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/bootstrap.php';

use Crawl\Controllers\Api\CrawlController;
use Crawl\Controllers\Api\SerpApiController;
use Crawl\Controllers\MigrationController;
use Crawl\Controllers\SerpController;
use Crawl\Controllers\WebController;
use Crawl\Lib\AuthMiddleware;
use Crawl\Lib\ErrorHandler;
use Crawl\Lib\Response;
use Crawl\Lib\Router;

ErrorHandler::register();
(new AuthMiddleware())->handle();

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$uriPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/';
$scriptDir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
$path = '/' . ltrim(substr($uriPath, strlen($scriptDir)), '/');
if ($path === '//') {
    $path = '/';
}

$body = json_decode(file_get_contents('php://input') ?: '', true);
if (!is_array($body)) {
    $body = $_POST;
}

$query = $_GET;

$web      = new WebController();
$api      = new CrawlController();
$serp     = new SerpController();
$serpApi  = new SerpApiController();
$router   = new Router();

$router->add('GET', '/',         fn() => $web->auditPage());
$router->add('GET', '/projects', fn() => $web->projectsPage());

// ── SERP Tracker pages ───────────────────────────────────────────────────────
$router->add('GET', '/serp',         fn() => $serp->indexPage());
$router->add('GET', '/serp/details', fn() => $serp->detailsPage());

// ── SERP Tracker API ─────────────────────────────────────────────────────────
$router->add('GET',    '/api/serp/run',                fn() => $serpApi->runSerpSse());
$router->add('GET',    '/api/serp/history',            fn() => $serpApi->getHistory());
$router->add('GET',    '/api/serp/run-detail',         fn() => $serpApi->getRunDetail());
$router->add('GET',    '/api/serp/export-csv',         fn() => $serpApi->exportCsv());
$router->add('GET',    '/api/serp/start-job',          fn() => $serpApi->startSerpJob());
$router->add('GET',    '/api/serp/process-job',        fn() => $serpApi->processJobEndpoint());
$router->add('GET',    '/api/serp/job-status',         fn() => $serpApi->getJobStatus());
$router->add('POST',   '/api/serp/submissions',        fn() => $serpApi->createSubmission());
$router->add('PUT',    '/api/serp/submissions/{id}',   function (array $p) use ($serpApi, $body): void { $serpApi->updateSubmission((int)$p['id'], $body); });
$router->add('DELETE', '/api/serp/submissions/{id}',   function (array $p) use ($serpApi): void        { $serpApi->deleteSubmission((int)$p['id']); });
$router->add('GET', '/report',         fn() => $web->reportPage());
$router->add('GET', '/client-report',  fn() => $web->clientReportPage());
$router->add('GET', '/migrate',  fn() => (new MigrationController())->run());

$router->add('POST', '/api/projects/{projectId}/crawl', function (array $params) use ($api, $body): void {
    $api->startCrawl((int)$params['projectId'], $body);
});
$router->add('GET', '/api/projects/{projectId}/crawl/{crawlRunId}', function (array $params) use ($api): void {
    $api->getRun((int)$params['projectId'], (int)$params['crawlRunId']);
});
$router->add('GET', '/api/projects/{projectId}/crawl-runs', function (array $params) use ($api): void {
    $api->listRuns((int)$params['projectId']);
});
$router->add('GET', '/api/projects/{projectId}/crawl-status/latest', function (array $params) use ($api): void {
    $api->latestStatus((int)$params['projectId']);
});
$router->add('GET', '/api/projects/{projectId}/website-audit', function (array $params) use ($api, $query): void {
    $api->websiteAudit((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/technical-issues', function (array $params) use ($api, $query): void {
    $api->technicalIssues((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/technical-issues-detail', function (array $params) use ($api, $query): void {
    $api->technicalDetail((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/website-level-summary', function (array $params) use ($api, $query): void {
    $api->websiteLevelSummary((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/page-detail', function (array $params) use ($api, $query): void {
    $api->pageDetail((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/crawl/{crawlRunId}/tabs', function (array $params) use ($api, $query): void {
    $api->tabs((int)$params['projectId'], (int)$params['crawlRunId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/crawl/{crawlRunId}/export', function (array $params) use ($api, $query): void {
    $api->export((int)$params['projectId'], (int)$params['crawlRunId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/website-audit-full', function (array $params) use ($api, $query): void {
    $api->fullAudit((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/health-score', function (array $params) use ($api, $query): void {
    $api->healthScore((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/duplicate-groups', function (array $params) use ($api, $query): void {
    $api->duplicateGroups((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/canonical-audit', function (array $params) use ($api, $query): void {
    $api->canonicalAudit((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/heading-audit', function (array $params) use ($api, $query): void {
    $api->headingAudit((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/link-equity', function (array $params) use ($api, $query): void {
    $api->linkEquity((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/crawl-budget', function (array $params) use ($api, $query): void {
    $api->crawlBudget((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/site-health', function (array $params) use ($api, $query): void {
    $api->siteHealth((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/crawl-comparison', function (array $params) use ($api, $query): void {
    $api->crawlComparison((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/schema-validation', function (array $params) use ($api, $query): void {
    $api->schemaValidation((int)$params['projectId'], $query);
});
$router->add('GET', '/api/projects/{projectId}/page-speed',        function (array $params) use ($api, $query): void { $api->pageSpeed((int)$params['projectId'], $query); });
$router->add('GET', '/api/projects/{projectId}/page-speed/stored', function (array $params) use ($api, $query): void { $api->pageSpeedStored((int)$params['projectId'], $query); });
$router->add('GET',    '/api/projects/health-summary',                                    function () use ($api): void                          { $api->healthSummary(); });

// Performance endpoints
$router->add('GET',    '/api/projects/{projectId}/performance/overview',               function (array $p) use ($api, $query): void         { $api->performanceOverview((int)$p['projectId'], $query); });
$router->add('GET',    '/api/projects/{projectId}/performance/top-pages',              function (array $p) use ($api, $query): void         { $api->performanceTopPages((int)$p['projectId'], $query); });
$router->add('GET',    '/api/projects/{projectId}/performance/trend',                  function (array $p) use ($api, $query): void         { $api->performanceTrend((int)$p['projectId'], $query); });
$router->add('GET',    '/api/projects/{projectId}/performance/search',                 function (array $p) use ($api, $query): void         { $api->performanceSearch((int)$p['projectId'], $query); });
$router->add('GET',    '/api/projects/{projectId}/performance/local',                  function (array $p) use ($api, $query): void         { $api->performanceLocal((int)$p['projectId'], $query); });

// OAuth endpoints
$router->add('GET',    '/api/projects/{projectId}/oauth/status',                       function (array $p) use ($api): void                 { $api->oauthStatus((int)$p['projectId']); });
$router->add('POST',   '/api/projects/{projectId}/oauth/connect',                      function (array $p) use ($api, $body): void          { $api->oauthConnect((int)$p['projectId'], $body); });
$router->add('POST',   '/api/projects/{projectId}/oauth/disconnect',                   function (array $p) use ($api, $body): void          { $api->oauthDisconnect((int)$p['projectId'], $body); });
$router->add('GET',    '/api/projects/{projectId}/auto-diff',             function (array $params) use ($api): void          { $api->autoDiff((int)$params['projectId']); });
$router->add('GET',    '/api/projects/{projectId}/categories',            function (array $params) use ($api): void          { $api->listCategories((int)$params['projectId']); });
$router->add('POST',   '/api/projects/{projectId}/categories',            function (array $params) use ($api, $body): void   { $api->createCategory((int)$params['projectId'], $body); });
$router->add('PUT',    '/api/projects/{projectId}/categories/{catId}',    function (array $params) use ($api, $body): void   { $api->updateCategory((int)$params['projectId'], (int)$params['catId'], $body); });
$router->add('DELETE', '/api/projects/{projectId}/categories/{catId}',    function (array $params) use ($api): void          { $api->deleteCategory((int)$params['projectId'], (int)$params['catId']); });

$dispatched = $router->dispatch($method, $path);
if (!$dispatched) {
    if (str_starts_with($path, '/api/')) {
        Response::error('Endpoint not found', 404);
    }

    http_response_code(404);
    echo 'Page not found';
}
