<?php

declare(strict_types=1);

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

use App\Services\BranchReadinessPolicy;

$remote = (string)($_SERVER['REMOTE_ADDR'] ?? '');
$isLocal = in_array($remote, ['127.0.0.1', '::1', 'localhost', ''], true);
$providedToken = (string)($_GET['token'] ?? '');
$expectedToken = trim((string)env('DDB_QA_TOKEN', ''));
$tokenOk = $expectedToken !== '' && hash_equals($expectedToken, $providedToken);

if (!$isLocal && !$tokenOk) {
    http_response_code(403);
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode(['status' => 'FAIL', 'error' => 'Forbidden']);
    exit;
}

$contract = BranchReadinessPolicy::contract();
$checks = [];

$add = static function (
    string $name,
    bool $ok,
    string $detail = ''
) use (&$checks): void {
    $checks[] = [
        'name' => $name,
        'status' => $ok ? 'PASS' : 'FAIL',
        'detail' => $detail,
    ];
};

$blocking = $contract['blocking_qa_branches'] ?? [];
$deferred = $contract['deferred_branches'] ?? [];
$dbUpdates = $contract['database_update_branches'] ?? [];

sort($blocking);
sort($deferred);
sort($dbUpdates);

$add(
    'blocking_qa_branches_exactly_njch_mnh',
    $blocking === ['mnh', 'njch'],
    implode(',', $blocking)
);

$add(
    'jckh_deferred_not_ready',
    $deferred === ['jckh']
    && BranchReadinessPolicy::state('jckh') === 'DEFERRED_NOT_READY',
    implode(',', $deferred)
);

$add(
    'jckh_non_blocking_business_qa',
    !BranchReadinessPolicy::isBlockingQa('jckh'),
    BranchReadinessPolicy::isBlockingQa('jckh') ? 'blocking' : 'non-blocking'
);

$add(
    'jckh_still_receives_database_updates',
    BranchReadinessPolicy::receivesDatabaseUpdates('jckh'),
    BranchReadinessPolicy::receivesDatabaseUpdates('jckh') ? 'included' : 'excluded'
);

$add(
    'database_update_scope_all_three_branches',
    $dbUpdates === ['jckh', 'mnh', 'njch'],
    implode(',', $dbUpdates)
);

$failures = count(
    array_filter(
        $checks,
        static function (array $check): bool {
            return $check['status'] === 'FAIL';
        }
    )
);

$result = [
    'schema_version' => '1.0',
    'phase' => 'H11.0-P4.5',
    'policy' => 'READY_BRANCHES_ONLY_JCKH_DEFERRED',
    'contract' => $contract,
    'checks' => $checks,
    'failures' => $failures,
    'status' => $failures === 0 ? 'PASS' : 'FAIL',
];

header('Content-Type: application/json; charset=UTF-8');

echo json_encode(
    $result,
    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
