<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, HEAD, OPTIONS, POST');
header('Access-Control-Allow-Headers: *');
header('X-Robots-Tag: all');

header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

set_error_handler(function ($severity, $message, $file, $line) {
    http_response_code(500);
    echo json_encode([
        'error' => 'PHP Error',
        'severity' => $severity,
        'message' => $message,
        'file' => $file,
        'line' => $line,
    ], JSON_PRETTY_PRINT);
    exit;
});

set_exception_handler(function ($e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Uncaught Exception',
        'type' => get_class($e),
        'message' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => explode("\n", $e->getTraceAsString()),
    ], JSON_PRETTY_PRINT);
    exit;
});


require_once __DIR__ . '/dataIndexLib.php';

if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

$built = buildDataIndex();
$index = $built['nodes'];
$indexSha256 = $built['indexSha256'];
header('X-Index-Sha256: ' . $indexSha256);

if (isset($_GET['meta'])) {
    // Opt-in wrapper; the default output stays the plain node list.
    echo json_encode([
        'indexSha256' => $indexSha256,
        'nodes' => $index,
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
} else {
    echo json_encode($index, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
