<?php
declare(strict_types=1);

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

use Analytics\Controllers\WebController;
use Analytics\Controllers\Api\AnalyticsController;
use Analytics\Controllers\Api\AiOverviewController;
use Analytics\Lib\Response;
use Analytics\Lib\Router;

$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)), '/');

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

$web    = new WebController();
$api    = new AnalyticsController();
$aiApi  = new AiOverviewController();
$router = new Router();

// ── Web routes ────────────────────────────────────────────────────────────────
$router->add('GET', '/',              fn() => $web->dashboard());
$router->add('GET', '/migrate',       fn() => $web->migrate());
$router->add('GET', '/projects/{id}', fn(array $p) => $web->projectShow((int)$p['id']));
$router->add('GET', '/report',        fn() => $web->reportViewer());
$router->add('GET', '/slides',        fn() => $web->reportSlides());

// ── API: Bulk Google Account Connect ─────────────────────────────────────
$router->add('GET',    '/api/bulk-connect',    function () use ($api): void { $api->bulkConnectRedirect(); });
$router->add('GET',    '/api/bulk-connect/status', function () use ($api): void { $api->bulkConnectStatus(); });
$router->add('DELETE', '/api/bulk-connect',    function () use ($api): void { $api->bulkDisconnect(); });

// ── API: Fetch (run tracker) ─────────────────────────────────────────────────
$router->add('POST', '/api/projects/{projectId}/fetch', function (array $p) use ($api, $body): void {
    $api->fetchProject((int)$p['projectId'], $body);
});
$router->add('POST', '/api/projects/fetch-all', function () use ($api, $body): void {
    $api->fetchAll($body);
});

// ── API: Snapshots ────────────────────────────────────────────────────────────
$router->add('GET', '/api/projects/{projectId}/snapshot',  function (array $p) use ($api, $query): void { $api->getSnapshot((int)$p['projectId'], $query); });
$router->add('GET', '/api/projects/{projectId}/snapshots', function (array $p) use ($api): void          { $api->listSnapshots((int)$p['projectId']); });

// ── API: Reports ──────────────────────────────────────────────────────────────
$router->add('GET', '/api/projects/{projectId}/report', function (array $p) use ($api, $query): void { $api->getReport((int)$p['projectId'], $query); });
$router->add('GET', '/api/projects/{projectId}/trend',  function (array $p) use ($api, $query): void { $api->getTrend((int)$p['projectId'], $query); });
$router->add('GET', '/api/manager-rollup',              function () use ($api, $query): void          { $api->getManagerRollup($query); });

// ── API: Export ───────────────────────────────────────────────────────────────
$router->add('GET', '/api/projects/{projectId}/export/excel', function (array $p) use ($api, $query): void { $api->exportExcel((int)$p['projectId'], $query); });
$router->add('GET', '/api/manager-rollup/export/excel',       function () use ($api, $query): void          { $api->exportManagerExcel($query); });

// ── API: Drill-down ───────────────────────────────────────────────────────────
$router->add('GET', '/api/projects/{projectId}/page-data',  function (array $p) use ($api, $query): void { $api->getPageData((int)$p['projectId'], $query); });
$router->add('GET', '/api/projects/{projectId}/query-data', function (array $p) use ($api, $query): void { $api->getQueryData((int)$p['projectId'], $query); });
$router->add('GET', '/api/projects/{projectId}/event-data', function (array $p) use ($api, $query): void { $api->getEventData((int)$p['projectId'], $query); });

// ── API: Fetch comparison period ─────────────────────────────────────────────
$router->add('POST', '/api/projects/{projectId}/fetch-comparison', function (array $p) use ($api, $body): void { $api->fetchComparison((int)$p['projectId'], $body); });

// ── API: Config update ────────────────────────────────────────────────────────
$router->add('POST', '/api/projects/{projectId}/config', function (array $p) use ($api, $body): void { $api->updateConfig((int)$p['projectId'], $body); });

// ── AI Overview: Web pages ────────────────────────────────────────────────────
$router->add('GET', '/ai-overview/{projectId}',                         fn(array $p) => $web->aiOverviewIndex((int)$p['projectId']));
$router->add('GET', '/ai-overview/{projectId}/prompt/{promptId}',       fn(array $p) => $web->aiOverviewDetail((int)$p['projectId'], (int)$p['promptId']));

// ── AI Overview: Prompt CRUD ──────────────────────────────────────────────────
$router->add('GET',    '/api/projects/{projectId}/ai-overview/prompts', function (array $p) use ($aiApi, $query): void { $aiApi->listPrompts((int)$p['projectId'], $query); });
$router->add('POST',   '/api/projects/{projectId}/ai-overview/prompts', function (array $p) use ($aiApi, $body):  void { $aiApi->addPrompt((int)$p['projectId'], $body); });
$router->add('DELETE', '/api/projects/{projectId}/ai-overview/prompts', function (array $p) use ($aiApi, $body):  void { $aiApi->deletePrompts((int)$p['projectId'], $body); });

// ── AI Overview: Run + history ────────────────────────────────────────────────
$router->add('POST', '/api/ai-overview/prompts/{promptId}/run',         function (array $p) use ($aiApi, $body): void { $aiApi->runPrompt((int)$p['promptId'], $body); });
$router->add('GET',  '/api/ai-overview/prompts/{promptId}/history',     function (array $p) use ($aiApi):        void { $aiApi->getHistory((int)$p['promptId']); });
$router->add('GET',  '/api/ai-overview/runs/{runId}',                   function (array $p) use ($aiApi):        void { $aiApi->getRun((int)$p['runId']); });

// ── AI Overview: Models ───────────────────────────────────────────────────────
$router->add('GET', '/api/ai-overview/models',                          function () use ($aiApi, $query):         void { $aiApi->getModels($query); });

// ── AI Overview: Competitors ──────────────────────────────────────────────────
$router->add('GET',    '/api/projects/{projectId}/ai-overview/competitors', function (array $p) use ($aiApi):             void { $aiApi->listCompetitors((int)$p['projectId']); });
$router->add('POST',   '/api/projects/{projectId}/ai-overview/competitors', function (array $p) use ($aiApi, $body):      void { $aiApi->addCompetitor((int)$p['projectId'], $body); });
$router->add('DELETE', '/api/ai-overview/competitors/{id}',                 function (array $p) use ($aiApi):             void { $aiApi->deleteCompetitor((int)$p['id']); });

// ── AI Overview: Brand & Domain Variations ────────────────────────────────────
$router->add('GET',    '/api/projects/{projectId}/ai-overview/variations',  function (array $p) use ($aiApi):             void { $aiApi->listVariations((int)$p['projectId']); });
$router->add('POST',   '/api/projects/{projectId}/ai-overview/variations',  function (array $p) use ($aiApi, $body):      void { $aiApi->addVariation((int)$p['projectId'], $body); });
$router->add('DELETE', '/api/ai-overview/variations/{id}',                  function (array $p) use ($aiApi, $query):     void { $aiApi->deleteVariation((int)$p['id'], $query['type'] ?? 'brand'); });

// ── Dispatch ──────────────────────────────────────────────────────────────────
if (!$router->dispatch($method, $path)) {
    if (str_starts_with($path, '/api/')) {
        Response::error('Endpoint not found', 404);
    } else {
        http_response_code(404);
        echo 'Page not found';
    }
}
