<?php
declare(strict_types=1);

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

use App\Repositories\OperationsRepository;
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 = OperationsRepository::shiftDateToYear($currentFrom, $compareYear);
$compareTo = OperationsRepository::shiftDateToYear($currentTo, $compareYear);

$repo = new OperationsRepository($hospital);
$scheduled = $repo->monthlyLegacyOperations($year, $compareYear, $currentFrom, $currentTo);
$performed = $repo->monthlyPerformedOperations($year, $compareYear, $currentFrom, $currentTo);
$cancelled = $repo->monthlyCancelledOperations($year, $compareYear, $currentFrom, $currentTo);
$currentSpecialties = $repo->topSpecialties($year, $currentFrom, $currentTo, 25);
$compareSpecialties = $repo->topSpecialties($compareYear, $compareFrom, $compareTo, 25);

function total(array $rows, string $key): float
{
    $sum = 0.0;
    foreach ($rows as $row) $sum += (float)($row[$key] ?? 0);
    return $sum;
}

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;
    }));
}

$lastMonth = (int)($contract['last_complete_month'] ?? 12);
$scheduledVisible = visibleRows($scheduled, $lastMonth);
$performedVisible = visibleRows($performed, $lastMonth);
$cancelledVisible = visibleRows($cancelled, $lastMonth);

$scheduledCurrent = total($scheduledVisible, 'current_value');
$scheduledCompare = total($scheduledVisible, 'compare_value');
$performedCurrent = total($performedVisible, 'current_value');
$performedCompare = total($performedVisible, '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_scheduled_months' => count($scheduledVisible) === 6,
    'six_performed_months' => count($performedVisible) === 6,
    'six_cancelled_months' => count($cancelledVisible) === 6,
    'scheduled_current_present' => $scheduledCurrent > 0,
    'scheduled_compare_present' => $scheduledCompare > 0,
    'performed_current_present' => $performedCurrent > 0,
    'performed_compare_present' => $performedCompare > 0,
    'current_specialties_present' => count($currentSpecialties) > 0,
    'compare_specialties_present' => count($compareSpecialties) > 0,
];

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

$result = [
    'schema' => 'DDB_OPERATIONS_R45_P9_LIVE_ACCEPTANCE_V1',
    'captured_at' => date(DATE_ATOM),
    'hospital' => $hospital,
    'year' => $year,
    'compare_year' => $compareYear,
    'contract' => $contract,
    'periods' => [
        'current_from' => $currentFrom,
        'current_to' => $currentTo,
        'compare_from' => $compareFrom,
        'compare_to' => $compareTo,
    ],
    'metrics' => [
        'scheduled_current' => $scheduledCurrent,
        'scheduled_compare' => $scheduledCompare,
        'performed_current' => $performedCurrent,
        'performed_compare' => $performedCompare,
        'current_specialty_count' => count($currentSpecialties),
        'compare_specialty_count' => count($compareSpecialties),
    ],
    'checks' => $checks,
    'status' => count($failed) === 0 ? 'PASS' : 'FAIL',
    'failed' => $failed,
    'oracle_writes' => 'NONE',
];

$dir = dirname(__DIR__) . '/storage/evidence/operations';
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
    throw new RuntimeException('Cannot create Operations evidence directory.');
}
$file = $dir . '/OPERATIONS_R45_P9_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);
