<?php
declare(strict_types=1);

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

use App\Repositories\VisitsRepository;

function timed(callable $callback): array
{
    $started = microtime(true);
    $value = $callback();
    return [$value, round((microtime(true) - $started) * 1000, 2)];
}

function canonical(array $rows): array
{
    $out = [];
    foreach ($rows as $row) {
        $month = (int)($row['month_id'] ?? 0);
        $out[$month] = [
            'current_value' => round((float)($row['current_value'] ?? 0), 6),
            'compare_value' => round((float)($row['compare_value'] ?? 0), 6),
        ];
    }
    ksort($out);
    return $out;
}

$hospital = strtolower((string)($argv[1] ?? 'njch'));
$year = (int)($argv[2] ?? date('Y'));
$compareYear = (int)($argv[3] ?? ($year - 1));
$iterations = max(1, min(5, (int)($argv[4] ?? 2)));

$runs = [];
$allParity = true;

for ($i = 1; $i <= $iterations; $i++) {
    // Separate repositories model independent reference calls and avoid sharing
    // request-level metadata state with the consolidated candidate.
    $candidateRepo = new VisitsRepository($hospital);
    list($bundle, $bundleMs) = timed(function () use ($candidateRepo, $year, $compareYear) {
        return $candidateRepo->monthlyVisitBundle($year, $compareYear);
    });

    $opdRepo = new VisitsRepository($hospital);
    list($opdReference, $opdMs) = timed(function () use ($opdRepo, $year, $compareYear) {
        return $opdRepo->monthlyOutpatientVisits($year, $compareYear);
    });

    $erRepo = new VisitsRepository($hospital);
    list($erReference, $erMs) = timed(function () use ($erRepo, $year, $compareYear) {
        return $erRepo->monthlyEmergencyVisits($year, $compareYear);
    });

    $opdParity = canonical($bundle['opd'] ?? []) === canonical($opdReference);
    $erParity = canonical($bundle['er'] ?? []) === canonical($erReference);
    $allParity = $allParity && $opdParity && $erParity;

    $runs[] = [
        'iteration' => $i,
        'bundle_ms' => $bundleMs,
        'separate_opd_ms' => $opdMs,
        'separate_er_ms' => $erMs,
        'separate_total_ms' => round($opdMs + $erMs, 2),
        'saved_ms' => round(($opdMs + $erMs) - $bundleMs, 2),
        'opd_parity' => $opdParity,
        'er_parity' => $erParity,
        'opd_months' => count($bundle['opd'] ?? []),
        'er_months' => count($bundle['er'] ?? []),
    ];
}

$result = [
    'schema' => 'DDB_VISITS_R45_P5_1_LIVE_ACCEPTANCE_V1',
    'captured_at' => date(DATE_ATOM),
    'hospital' => $hospital,
    'year' => $year,
    'compare_year' => $compareYear,
    'iterations' => $iterations,
    'status' => $allParity ? 'PASS' : 'FAIL',
    'numeric_parity' => $allParity,
    'runs' => $runs,
    'oracle_writes' => 'NONE',
];

$dir = dirname(__DIR__) . '/storage/evidence/visits-performance';
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
    throw new RuntimeException('Cannot create Visits evidence directory.');
}
$file = $dir . '/VISITS_R45_P5_1_LIVE_ACCEPTANCE_' . date('Ymd_His') . '.json';
file_put_contents($file, json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);

echo json_encode($result + ['evidence_file' => $file], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($allParity ? 0 : 1);
