<?php
declare(strict_types=1);

function biblebot_specs_json(int $status, array $payload): never
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store');
    header('X-Content-Type-Options: nosniff');
    echo json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
    exit;
}

$https = strtolower((string)($_SERVER['HTTPS'] ?? ''));
$port = (string)($_SERVER['SERVER_PORT'] ?? '');
if (!in_array($https, ['on','1'], true) && $port !== '443') {
    biblebot_specs_json(400, ['ok'=>false,'error'=>'INVALID_REQUEST']);
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    biblebot_specs_json(400, ['ok'=>false,'error'=>'INVALID_REQUEST']);
}

$keySource = __DIR__ . '/gpt-session.php';
if (!is_file($keySource) || !is_readable($keySource)) {
    biblebot_specs_json(503, ['ok'=>false,'error'=>'TEMPORARILY_UNAVAILABLE']);
}
$keySourceText = file_get_contents($keySource);
if (
    !is_string($keySourceText)
    || preg_match("/const\s+BIBLEBOT_ACTION_KEY\s*=\s*'([a-f0-9]{64})'\s*;/", $keySourceText, $m) !== 1
) {
    biblebot_specs_json(503, ['ok'=>false,'error'=>'TEMPORARILY_UNAVAILABLE']);
}
$configuredKey = $m[1];
$presented = (string)($_SERVER['HTTP_X_WW_ACTION_KEY'] ?? '');

if (
    preg_match('/^[a-f0-9]{64}$/', $presented) !== 1
    || !hash_equals($configuredKey, $presented)
) {
    biblebot_specs_json(401, ['ok'=>false,'error'=>'ACTION_UNAUTHORIZED']);
}

$raw = file_get_contents('php://input');
if (!is_string($raw) || strlen($raw) < 2 || strlen($raw) > 131072) {
    biblebot_specs_json(400, ['ok'=>false,'error'=>'INVALID_REQUEST']);
}
try {
    $body = json_decode($raw, true, 64, JSON_THROW_ON_ERROR);
    if (!is_array($body)) {
        throw new InvalidArgumentException('INVALID_REQUEST');
    }

    $allowedTop = ['endpoint','name','version','selectors','maxBatchContentBytes','chunkIndex','chunkSize','etag'];
    foreach (array_keys($body) as $k) {
        if (!in_array($k, $allowedTop, true)) {
            throw new InvalidArgumentException('INVALID_REQUEST');
        }
    }

    $endpoint = $body['endpoint'] ?? null;
    if (!is_string($endpoint) || $endpoint === '') {
        throw new InvalidArgumentException('INVALID_REQUEST');
    }

    require_once '/home/eeewmxxw/biblebot-private/biblebot_governance_spec_service.php';
    $service = new BibleBotGovernanceSpecService('/home/eeewmxxw/biblebot-private/bbgov');

    if ($endpoint === 'listBundleSpecs') {
        biblebot_specs_json(200, $service->listBundleSpecs());
    }

    if ($endpoint === 'getBundleSpec') {
        $name = is_string($body['name'] ?? null) ? $body['name'] : '';
        $version = array_key_exists('version', $body) && is_string($body['version']) ? $body['version'] : null;
        biblebot_specs_json(200, $service->getBundleSpec($name, $version));
    }

    if ($endpoint === 'getBundleSpecs') {
        $selectors = $body['selectors'] ?? null;
        $cap = $body['maxBatchContentBytes'] ?? 65000;
        if (!is_array($selectors) || !is_int($cap)) {
            throw new InvalidArgumentException('INVALID_REQUEST');
        }
        biblebot_specs_json(200, $service->getBundleSpecs($selectors, $cap));
    }

    if ($endpoint === 'getBundleSpecChunk') {
        $name = is_string($body['name'] ?? null) ? $body['name'] : '';
        $version = array_key_exists('version', $body) && is_string($body['version']) ? $body['version'] : null;
        $chunkIndex = $body['chunkIndex'] ?? null;
        $chunkSize = $body['chunkSize'] ?? 58000;
        $etag = array_key_exists('etag', $body) && is_string($body['etag']) ? $body['etag'] : null;
        if (!is_int($chunkIndex) || !is_int($chunkSize)) {
            throw new InvalidArgumentException('INVALID_REQUEST');
        }
        biblebot_specs_json(200, $service->getBundleSpecChunk($name, $version, $chunkIndex, $chunkSize, $etag));
    }

    biblebot_specs_json(400, ['ok'=>false,'error'=>'INVALID_REQUEST']);
} catch (InvalidArgumentException $e) {
    biblebot_specs_json(400, ['ok'=>false,'error'=>'INVALID_REQUEST']);
} catch (RuntimeException $e) {
    $m = strtoupper($e->getMessage());
    if ($m === 'SPEC_NOT_FOUND') {
        biblebot_specs_json(404, ['ok'=>false,'error'=>'SPEC_NOT_FOUND']);
    }
    if ($m === 'SPEC_AMBIGUOUS') {
        biblebot_specs_json(409, ['ok'=>false,'error'=>'SPEC_AMBIGUOUS']);
    }
    if ($m === 'BATCH_CONTENT_LIMIT_EXCEEDED') {
        biblebot_specs_json(413, ['ok'=>false,'error'=>'BATCH_CONTENT_LIMIT_EXCEEDED']);
    }
    if ($m === 'ETAG_MISMATCH') {
        biblebot_specs_json(409, ['ok'=>false,'error'=>'ETAG_MISMATCH']);
    }
    biblebot_specs_json(503, ['ok'=>false,'error'=>'TEMPORARILY_UNAVAILABLE']);
} catch (Throwable $e) {
    biblebot_specs_json(503, ['ok'=>false,'error'=>'TEMPORARILY_UNAVAILABLE']);
}
