<?php

declare(strict_types=1);

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

use App\Services\BranchOracleAccessResolver;
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;
}

$activeBranches = BranchReadinessPolicy::blockingQaBranches();
$deferredBranches = BranchReadinessPolicy::deferredBranches();
$checks = [];
$branchResults = [];
$resolver = new BranchOracleAccessResolver();

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

foreach ($activeBranches as $branch) {
    try {
        $resolution = $resolver->resolve($branch);

        $branchResults[$branch] = [
            'status' => 'PASS',
            'readiness_state' => BranchReadinessPolicy::state($branch),
            'resolution' => $resolution,
        ];

        $add(
            $branch . '_oracle_identity_verified',
            true,
            'mode=' . (string)($resolution['mode'] ?? '')
        );
    } catch (Throwable $error) {
        $branchResults[$branch] = [
            'status' => 'FAIL',
            'readiness_state' => BranchReadinessPolicy::state($branch),
            'error' => $error->getMessage(),
        ];

        $add(
            $branch . '_oracle_identity_verified',
            false,
            $error->getMessage()
        );
    }
}

foreach ($deferredBranches as $branch) {
    $branchResults[$branch] = [
        'status' => 'DEFERRED_NOT_READY',
        'readiness_state' => BranchReadinessPolicy::state($branch),
        'blocking_qa' => false,
        'database_updates' => BranchReadinessPolicy::receivesDatabaseUpdates($branch),
    ];

    $add(
        $branch . '_deferred_non_blocking',
        !BranchReadinessPolicy::isBlockingQa($branch),
        'state=' . BranchReadinessPolicy::state($branch)
    );
}

$fingerprints = [];
$collision = false;

foreach ($activeBranches as $branch) {
    $fingerprint = (string)(
        $branchResults[$branch]['resolution']['identity']['fingerprint'] ?? ''
    );

    if ($fingerprint === '') {
        continue;
    }

    if (isset($fingerprints[$fingerprint])) {
        $collision = true;
    }

    $fingerprints[$fingerprint] = $branch;
}

$add(
    'ready_branch_identity_fingerprints_distinct',
    !$collision && count($fingerprints) === count($activeBranches),
    count($fingerprints) . '/' . count($activeBranches)
);

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

$result = [
    'schema_version' => '2.0',
    'phase' => 'H11.0-P4.5',
    'policy' => 'READY_BRANCHES_ONLY_JCKH_DEFERRED',
    'active_qa_branches' => $activeBranches,
    'deferred_branches' => $deferredBranches,
    'database_update_branches' => BranchReadinessPolicy::databaseUpdateBranches(),
    'branches' => $branchResults,
    'diagnostics' => $resolver->diagnostics(),
    'checks' => $checks,
    'write_operations' => 'NONE',
    '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
);
