<?php

declare(strict_types=1);

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

use App\Repositories\ExecutiveSummaryRepository;

/**
 * R42 read-only live reconciliation tool.
 *
 * Examples:
 *   php tools/executive-kpi-reconcile.php --hospital=njch
 *   php tools/executive-kpi-reconcile.php --hospitals=njch,mnh
 *
 * The tool never refreshes or writes Oracle data. It compares the eight live
 * Legacy KPI SQL contracts with the current DASH_EXEC_SUMMARY_KPI values.
 */

$options = getopt('', ['hospital::', 'hospitals::']);
$requested = '';
if (isset($options['hospitals']) && is_string($options['hospitals'])) {
    $requested = $options['hospitals'];
} elseif (isset($options['hospital']) && is_string($options['hospital'])) {
    $requested = $options['hospital'];
}
if (trim($requested) === '') {
    $requested = (string)env('EXECUTIVE_REFRESH_HOSPITALS', 'njch');
}

$hospitals = array_values(array_unique(array_filter(array_map(
    static function (string $value): string { return strtolower(trim($value)); },
    explode(',', $requested)
), static function (string $value): bool { return $value !== ''; })));

if (!$hospitals) {
    $hospitals = ['njch'];
}

$started = microtime(true);
$result = [
    'patch' => 'H11.0-P11.1-R42.1',
    'target' => '11.0.11.50',
    'contract' => ExecutiveSummaryRepository::LEGACY_KPI_CONTRACT,
    'status' => 'FAIL',
    'required_exact_parity' => '8/8 PER HOSPITAL',
    'oracle_writes' => 'NONE',
    'hospitals' => [],
    'pass_hospitals' => 0,
    'fail_hospitals' => 0,
    'unavailable_hospitals' => 0,
    'truth_boundary' => 'PASS requires exact 8/8 live legacy SQL versus current summary values. Missing or stale evidence is not PASS.',
];

foreach ($hospitals as $hospital) {
    try {
        $reconciliation = (new ExecutiveSummaryRepository($hospital))->reconcileLegacyKpisAgainstSummary();
        $result['hospitals'][$hospital] = $reconciliation;
        if (($reconciliation['status'] ?? '') === 'PASS'
            && (int)($reconciliation['pass_metrics'] ?? 0) === 8
            && (int)($reconciliation['fail_metrics'] ?? 0) === 0
        ) {
            $result['pass_hospitals']++;
        } elseif (($reconciliation['status'] ?? '') === 'UNAVAILABLE') {
            $result['unavailable_hospitals']++;
            $result['fail_hospitals']++;
        } else {
            $result['fail_hospitals']++;
        }
    } catch (Throwable $e) {
        $result['hospitals'][$hospital] = [
            'hospital' => strtoupper($hospital),
            'status' => 'FAIL',
            'pass_metrics' => 0,
            'fail_metrics' => 8,
            'total_metrics' => 8,
            'error' => $e->getMessage(),
            'exception' => get_class($e),
            'oracle_writes' => 'NONE',
        ];
        $result['fail_hospitals']++;
    }
}

$result['status'] = ($result['fail_hospitals'] === 0 && $result['pass_hospitals'] === count($hospitals))
    ? 'PASS'
    : (($result['unavailable_hospitals'] === count($hospitals)) ? 'UNAVAILABLE' : 'FAIL');
$result['elapsed_ms'] = (int)round((microtime(true) - $started) * 1000);
$result['generated_at'] = date('c');

echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($result['status'] === 'PASS' ? 0 : 1);
