<?php

declare(strict_types=1);

$root = dirname(__DIR__);
$summaryPath = $root . '/app/Repositories/ExecutiveSummaryRepository.php';
$reconcilePath = $root . '/tools/executive-kpi-reconcile.php';
$versionPath = $root . '/DDB_VERSION.json';

$summary = (string)@file_get_contents($summaryPath);
$reconcile = (string)@file_get_contents($reconcilePath);
$version = json_decode((string)@file_get_contents($versionPath), true);

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

$add('R42.1 version contract', ($version['release'] ?? '') === '11.0.11.50' && ($version['phase'] ?? '') === 'H11.0-P11.1-R42.1');
$add('R42.1 incident metadata exists', isset($version['r42_1_legacy_kpi_column_ownership_hotfix']));
$add('No Oracle schema changes', ($version['database_changes'] ?? '') === 'NONE');
$add('No Oracle business data writes by patch', ($version['oracle_write_operations'] ?? '') === 'NONE');

$start = strpos($summary, 'private function opdVisitsToday(): ?float');
$end = strpos($summary, 'private function admissionsToday(): ?float');
$block = ($start !== false && $end !== false && $end > $start) ? substr($summary, $start, $end - $start) : '';

$add('Affected four-metric Legacy block found', $block !== '');
$add('Wrong reservation alias CLASSCODE qualification removed', !str_contains($block, 'WHERE r.classcode = 2'));
$add('CLASSCODE exact-one-owner resolver is used four times', substr_count($block, "legacyVisitReservationColumnExpr('CLASSCODE')") === 4);
$add('Resolved CLASSCODE expression is injected into all four SQL contracts', substr_count($block, 'WHERE {$classCodeExpr} = 2') === 4);
$add('OPD still preserves exact Legacy status and schedule predicates', str_contains($block, "r.servstatus NOT IN ('C','F')") && str_contains($block, 'r.sched_serial IS NOT NULL'));
$add('ER still preserves exact Legacy emergency classifier', str_contains($block, 'NVL({$emergencyTypeExpr},0) = 1 OR {$clinicExpr} IN (16, 297, 298)'));
$add('Follow-up still preserves RES_TYPE = 1', str_contains($block, 'AND r.res_type = 1'));
$add('First visits still preserves VISIT_ID = 1', str_contains($block, 'AND v.visit_id = 1'));
$add('Per-KPI refresh logging is contextual', str_contains($summary, "'legacy_kpi.opd'") && str_contains($summary, "'legacy_kpi.first_visits'"));
$add('Reconciliation snapshot isolates per-metric SQL failures', str_contains($summary, "'reconcile.opd'") && str_contains($summary, "'reconcile.performed_operations'"));
$add('safeNumber supports contextual logging', str_contains($summary, 'private function safeNumber(callable $fn, string $context = \'safeNumber\'): ?float') && str_contains($summary, '$this->log($context, $e);'));
$add('Reconciliation metadata points to R42.1 target', str_contains($reconcile, "'patch' => 'H11.0-P11.1-R42.1'") && str_contains($reconcile, "'target' => '11.0.11.50'"));
$add('Live 8/8 acceptance remains mandatory', str_contains($reconcile, "'required_exact_parity' => '8/8 PER HOSPITAL'"));
$add('Official baseline is not pre-claimed', (($version['r42_1_legacy_kpi_column_ownership_hotfix']['official_baseline_claimed'] ?? true) === false));

$pass = count(array_filter($gates, static fn(array $g): bool => $g['status'] === 'PASS'));
$fail = count($gates) - $pass;
$out = [
    'patch' => 'H11.0-P11.1-R42.1',
    'target' => '11.0.11.50',
    'status' => $fail === 0 ? 'PASS' : 'FAIL',
    'pass_gates' => $pass,
    'fail_gates' => $fail,
    'total_gates' => count($gates),
    'incident_signature' => 'OPD_ER_FOLLOW_UP_FIRST_VISITS_DASH_AFTER_R42',
    'root_cause' => 'Wrong hard-coded r.classcode ownership in the four RCP_VISIT + RCP_SERVICE_RESERVATION Legacy KPI queries.',
    'required_live_gate' => 'Refresh summary, then exact 8/8 live reconciliation and browser acceptance.',
    'gates' => $gates,
    'truth_boundary' => 'Static PASS is not Live Oracle acceptance. Missing values are not PASS.',
];

echo json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), PHP_EOL;
exit($fail === 0 ? 0 : 1);
