<?php

declare(strict_types=1);

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

use App\Services\LegacyMissingRouteDiscoveryService;

$root = dirname(__DIR__);
$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;
}

$checks = [];

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

$version = [];
if (is_file($root . '/DDB_VERSION.json')) {
    $decoded = json_decode(
        (string)file_get_contents($root . '/DDB_VERSION.json'),
        true
    );
    $version = is_array($decoded) ? $decoded : [];
}

$release = (string)($version['release'] ?? '');

$layoutSource = is_file($root . '/app/Views/layouts/main.php')
    ? (string)file_get_contents($root . '/app/Views/layouts/main.php')
    : '';

$frontControllerSource = is_file($root . '/public/index.php')
    ? (string)file_get_contents($root . '/public/index.php')
    : '';

$serviceSource = is_file(
    $root . '/app/Services/LegacyMissingRouteDiscoveryService.php'
)
    ? (string)file_get_contents(
        $root . '/app/Services/LegacyMissingRouteDiscoveryService.php'
    )
    : '';

$add('target_release_11_0_10', $release === '11.0.10', $release);

$add(
    'quality_current_nav_placeholder_is_inactive',
    strpos($layoutSource, "'page' => 'quality'") !== false
    && preg_match(
        "/'page'\\s*=>\\s*'quality'.*?'live'\\s*=>\\s*false/s",
        $layoutSource
    ) === 1,
    'quality nav entry exists with live=false'
);

$add(
    'branch_comparison_current_nav_placeholder_is_inactive',
    strpos($layoutSource, "'page' => 'branch-comparison'") !== false
    && preg_match(
        "/'page'\\s*=>\\s*'branch-comparison'.*?'live'\\s*=>\\s*false/s",
        $layoutSource
    ) === 1,
    'branch-comparison nav entry exists with live=false'
);

$add(
    'no_active_quality_route_handler_introduced',
    strpos($frontControllerSource, "'quality'") === false
    && strpos($frontControllerSource, '"quality"') === false,
    'No public route handler introduced by P10'
);

$add(
    'no_active_branch_comparison_route_handler_introduced',
    strpos($frontControllerSource, "'branch-comparison'") === false
    && strpos($frontControllerSource, '"branch-comparison"') === false,
    'No public route handler introduced by P10'
);

$combined = strtolower($serviceSource);
$writeDetected = preg_match(
    '/\b(insert\s+into|update\s+[a-z0-9_]+\s+set|delete\s+from|'
    . 'create\s+table|alter\s+table|drop\s+table|merge\s+into)\b/i',
    $combined
) === 1;

$add(
    'oracle_write_operations_none',
    !$writeDetected,
    'Discovery service reads local registries only'
);

$discovery = null;
$liveError = '';

try {
    $discovery = (new LegacyMissingRouteDiscoveryService())->run($root);

    $add(
        'reviewed_routes_2_of_2',
        (int)($discovery['reviewed_count'] ?? 0) === 2,
        (string)($discovery['reviewed_count'] ?? 0) . '/2'
    );

    $add(
        'resolved_routes_2_of_2',
        (int)($discovery['resolved_count'] ?? 0) === 2,
        (string)($discovery['resolved_count'] ?? 0) . '/2'
    );

    $add(
        'historical_dispatcher_keys_31',
        (int)($discovery['historical_dispatcher_key_count'] ?? 0) === 31,
        (string)($discovery['historical_dispatcher_key_count'] ?? 0)
    );

    $add(
        'historical_function_matrix_rows_31',
        (int)($discovery['historical_function_matrix_rows'] ?? 0) === 31,
        (string)($discovery['historical_function_matrix_rows'] ?? 0)
    );

    $add(
        'reviewed_routes_have_zero_proven_historical_contracts',
        (int)($discovery['proven_historical_contracts'] ?? -1) === 0,
        (string)($discovery['proven_historical_contracts'] ?? 'missing')
    );

    $discoveries = (array)($discovery['discoveries'] ?? []);
    $quality = [];
    $branchComparison = [];

    foreach ($discoveries as $row) {
        if (($row['route'] ?? '') === 'quality') {
            $quality = $row;
        }
        if (($row['route'] ?? '') === 'branch-comparison') {
            $branchComparison = $row;
        }
    }

    $add(
        'quality_disposition_correct',
        ($quality['disposition'] ?? '') ===
            'OUT_OF_LEGACY_SCOPE_PENDING_HISTORICAL_EVIDENCE'
        && ($quality['historical_dispatcher_key_found'] ?? true) === false
        && ($quality['historical_function_matrix_row_found'] ?? true) === false
        && ($quality['historical_oracle_contract_found'] ?? true) === false,
        (string)($quality['disposition'] ?? 'missing')
    );

    $add(
        'branch_comparison_disposition_correct',
        ($branchComparison['disposition'] ?? '') ===
            'OUT_OF_LEGACY_SCOPE_PENDING_HISTORICAL_EVIDENCE'
        && ($branchComparison['historical_dispatcher_key_found'] ?? true) === false
        && ($branchComparison['historical_function_matrix_row_found'] ?? true) === false
        && ($branchComparison['historical_oracle_contract_found'] ?? true) === false,
        (string)($branchComparison['disposition'] ?? 'missing')
    );

    $scope = (array)($discovery['parity_scope_correction'] ?? []);

    $add(
        'legacy_parity_population_corrected_to_29',
        (int)($scope['evidenced_legacy_parity_population'] ?? 0) === 29,
        (string)($scope['evidenced_legacy_parity_population'] ?? 0)
    );

    $add(
        'legacy_matched_23',
        (int)($scope['matched'] ?? 0) === 23,
        (string)($scope['matched'] ?? 0)
    );

    $add(
        'legacy_partial_6',
        (int)($scope['partial_deferred_branch'] ?? 0) === 6,
        (string)($scope['partial_deferred_branch'] ?? 0)
    );

    $add(
        'legacy_missing_zero',
        (int)($scope['missing'] ?? -1) === 0
        && (int)($discovery['legacy_missing_after_correction'] ?? -1) === 0,
        '0'
    );

    $add(
        'legacy_progress_79_3',
        abs((float)($scope['matched_pct'] ?? 0) - 79.3) < 0.000001,
        (string)($scope['matched_pct'] ?? 0)
    );

    $partialProof = (array)($discovery['partial_ready_scope_proof'] ?? []);

    $add(
        'all_six_partial_functions_ready_scope_proven',
        (int)($partialProof['proven'] ?? 0) === 6
        && (int)($partialProof['of_partial_functions'] ?? 0) === 6
        && (int)($partialProof['remaining_unproven'] ?? -1) === 0,
        '6/6; remaining=0'
    );

    $add(
        'historical_evidence_boundary_explicit',
        strpos(
            (string)($discovery['evidence_boundary'] ?? ''),
            'FULL_HISTORICAL_DISPATCHER_BLOCK_RECOVERED'
        ) !== false
        && strpos(
            (string)($discovery['evidence_boundary'] ?? ''),
            'FULL_HISTORICAL_SITE_ARCHIVE_NOT_AVAILABLE'
        ) !== false,
        (string)($discovery['evidence_boundary'] ?? '')
    );

    $add(
        'live_read_only',
        ($discovery['write_operations'] ?? '') === 'NONE',
        (string)($discovery['write_operations'] ?? 'unknown')
    );
} catch (Throwable $error) {
    $liveError = $error->getMessage();

    $add('reviewed_routes_2_of_2', false, 'Execution error');
    $add('resolved_routes_2_of_2', false, 'Execution error');
    $add('historical_dispatcher_keys_31', false, 'Execution error');
    $add('historical_function_matrix_rows_31', false, 'Execution error');
    $add(
        'reviewed_routes_have_zero_proven_historical_contracts',
        false,
        'Execution error'
    );
    $add('quality_disposition_correct', false, 'Execution error');
    $add('branch_comparison_disposition_correct', false, 'Execution error');
    $add('legacy_parity_population_corrected_to_29', false, 'Execution error');
    $add('legacy_matched_23', false, 'Execution error');
    $add('legacy_partial_6', false, 'Execution error');
    $add('legacy_missing_zero', false, 'Execution error');
    $add('legacy_progress_79_3', false, 'Execution error');
    $add('all_six_partial_functions_ready_scope_proven', false, 'Execution error');
    $add(
        'historical_evidence_boundary_explicit',
        true,
        'Boundary remains fail-closed'
    );
    $add('live_read_only', true, 'NONE');
}

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

$result = [
    'schema_version' => '1.0',
    'phase' => 'H11.0-P10',
    'title' => 'Missing Routes Discovery & Exact Contract Recovery Batch',
    'reviewed_routes' => ['quality', 'branch-comparison'],
    'write_operations' => 'NONE',
    'checks' => $checks,
    'discovery' => $discovery,
    'live_error' => $liveError,
    'pass_gates' => count($checks) - $failures,
    'fail_gates' => $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
);
