<?php

declare(strict_types=1);

$root = dirname(__DIR__);
$version = json_decode((string)file_get_contents($root . '/DDB_VERSION.json'), true);
$repo = (string)file_get_contents($root . '/app/Repositories/BranchComparisonRepository.php');
$live = (string)file_get_contents($root . '/tools/branch-comparison-r45-p11-2-live-acceptance.php');
$diag = (string)file_get_contents($root . '/tools/branch-comparison-emergency-column-diagnostic.php');
$env = (string)file_get_contents($root . '/.env');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.92',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P11.2.3',
    'qualified_clinic_removed' => strpos($repo, 'r.clinic_id') === false,
    'qualified_emergency_type_removed' => strpos($repo, 'r.outpta_emergency_type') === false,
    'legacy_unqualified_emergency_type' => strpos($repo, 'NVL(outpta_emergency_type, 0) = 1') !== false,
    'legacy_unqualified_clinic' => strpos($repo, 'clinic_id IN (16, 297, 298)') !== false,
    'legacy_contract_comment' => strpos($repo, 'Preserve the exact legacy discriminator') !== false,
    'order_hotfix_preserved' => strpos($repo, 'ORDER BY 1, 2') !== false,
    'six_union_contract_preserved' => substr_count($repo, 'UNION ALL') === 5,
    'live_acceptance_catches_throwable' => strpos($live, 'catch (\\Throwable $error)') !== false,
    'live_acceptance_structured_error' => strpos($live, "'error_code' => \$errorCode") !== false,
    'live_acceptance_continues' => strpos($live, 'continue;') !== false,
    'column_diagnostic_present' => strpos($diag, 'BRANCH_COMPARISON_EMERGENCY_COLUMN_DIAGNOSTIC_V1') !== false,
    'diagnostic_read_only' => strpos($diag, "FROM all_tab_columns") !== false,
    'revenue_summary_enabled_preserved' => preg_match('/^USE_REVENUE_SUMMARY=1$/m', $env) === 1,
    'revenue_summary_age_preserved' => preg_match('/^REVENUE_SUMMARY_MAX_AGE_HOURS=30$/m', $env) === 1,
    'oracle_writes_none' => ($version['r45_p11_2_3']['oracle_writes'] ?? '') === 'NONE',
];

$failed = [];
foreach ($checks as $name => $passed) {
    if (!$passed) $failed[] = $name;
}

echo json_encode([
    'schema' => 'R45_P11_2_3_STATIC_QA',
    'checks' => $checks,
    'passed' => count($checks) - count($failed),
    'failed' => $failed,
    'oracle_writes' => 'NONE',
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;

exit($failed === [] ? 0 : 1);
