<?php
declare(strict_types=1);

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

use App\Repositories\DiagnosticsRepository;
use App\Services\FairYearComparisonPolicy;

$hospital = strtolower((string)($argv[1] ?? 'njch'));
$year = (int)($argv[2] ?? date('Y'));
$compareYear = (int)($argv[3] ?? ($year - 1));

$contract = (new FairYearComparisonPolicy())->resolve($year, $compareYear);
$currentFrom = (string)($contract['from_date'] ?? sprintf('%04d-01-01', $year));
$currentTo = (string)($contract['to_date'] ?? sprintf('%04d-12-31', $year));
$compareFrom = DiagnosticsRepository::shiftDateToYear($currentFrom, $compareYear);
$compareTo = DiagnosticsRepository::shiftDateToYear($currentTo, $compareYear);
$lastMonth = (int)($contract['last_complete_month'] ?? 12);

$repo = new DiagnosticsRepository($hospital);
$labRows = $repo->monthlyLabTests($year, $compareYear, $currentFrom, $currentTo);
$radiologyRows = $repo->monthlyRadiologyTests($year, $compareYear, $currentFrom, $currentTo);

function visibleRows(array $rows, int $lastMonth): array
{
    return array_values(array_filter($rows, static function (array $row) use ($lastMonth): bool {
        $month = (int)($row['month_id'] ?? 0);
        return $month >= 1 && $month <= $lastMonth;
    }));
}
function total(array $rows, string $key): float
{
    $sum = 0.0;
    foreach ($rows as $row) $sum += (float)($row[$key] ?? 0);
    return $sum;
}

$labVisible = visibleRows($labRows, $lastMonth);
$radiologyVisible = visibleRows($radiologyRows, $lastMonth);

$metrics = [
    'lab_current' => total($labVisible, 'current_value'),
    'lab_compare' => total($labVisible, 'compare_value'),
    'radiology_current' => total($radiologyVisible, 'current_value'),
    'radiology_compare' => total($radiologyVisible, 'compare_value'),
];

$checks = [
    'fair_contract' => !empty($contract['fair_current_year_comparison']),
    'last_complete_month_is_6' => $lastMonth === 6,
    'current_period_exact' => $currentFrom === '2026-01-01' && $currentTo === '2026-06-30',
    'compare_period_exact' => $compareFrom === '2025-01-01' && $compareTo === '2025-06-30',
    'six_lab_months' => count($labVisible) === 6,
    'six_radiology_months' => count($radiologyVisible) === 6,
    'lab_current_present' => $metrics['lab_current'] > 0,
    'lab_compare_present' => $metrics['lab_compare'] > 0,
    'radiology_current_present' => $metrics['radiology_current'] > 0,
    'radiology_compare_present' => $metrics['radiology_compare'] > 0,
];

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

$result = [
    'schema' => 'DDB_DIAGNOSTICS_R45_P10_LIVE_ACCEPTANCE_V1',
    'captured_at' => date(DATE_ATOM),
    'hospital' => $hospital,
    'periods' => [
        'current_from' => $currentFrom,
        'current_to' => $currentTo,
        'compare_from' => $compareFrom,
        'compare_to' => $compareTo,
    ],
    'metrics' => $metrics,
    'checks' => $checks,
    'status' => count($failed) === 0 ? 'PASS' : 'FAIL',
    'failed' => $failed,
    'oracle_writes' => 'NONE',
];

$dir = dirname(__DIR__) . '/storage/evidence/diagnostics';
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
    throw new RuntimeException('Cannot create Diagnostics evidence directory.');
}
$file = $dir . '/DIAGNOSTICS_R45_P10_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(count($failed) === 0 ? 0 : 1);
