<?php
declare(strict_types=1);

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

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

$repo = new BedsRepository($hospital);
$currentUnits = $repo->legacyCompatibleUnitEfficiencyRows($year, $currentFrom, $currentTo, 0);
$compareUnits = $repo->legacyCompatibleUnitEfficiencyRows($compareYear, $compareFrom, $compareTo, 0);

function weighted(array $rows): ?float
{
    $occupied = 0.0;
    $possible = 0.0;
    foreach ($rows as $row) {
        $occupied += (float)($row['total_hours_occupied'] ?? 0);
        $possible += (float)($row['total_hours_period'] ?? 0);
    }
    return $possible > 0 ? ($occupied / $possible) * 100 : null;
}

function validRows(array $rows): bool
{
    foreach ($rows as $row) {
        $value = (float)($row['bed_efficiency_percentage'] ?? -1);
        if ($value < 0 || !is_finite($value)) {
            return false;
        }
    }
    return true;
}

$currentWeighted = weighted($currentUnits);
$compareWeighted = weighted($compareUnits);

$checks = [
    'fair_contract' => !empty($contract['fair_current_year_comparison']),
    'last_complete_month_is_6' => (int)($contract['last_complete_month'] ?? 0) === 6,
    'current_period' => $currentFrom === '2026-01-01' && $currentTo === '2026-06-30',
    'compare_period' => $compareFrom === '2025-01-01' && $compareTo === '2025-06-30',
    'current_units_present' => count($currentUnits) > 0,
    'compare_units_present' => count($compareUnits) > 0,
    'current_rows_valid' => validRows($currentUnits),
    'compare_rows_valid' => validRows($compareUnits),
    'current_weighted_available' => $currentWeighted !== null,
    'compare_weighted_available' => $compareWeighted !== null,
];

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

$result = [
    'schema' => 'DDB_BEDS_R45_P8_1_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' => [
        'current_unit_count' => count($currentUnits),
        'compare_unit_count' => count($compareUnits),
        'current_weighted_utilization' => $currentWeighted,
        'compare_weighted_utilization' => $compareWeighted,
        'movement_pp' => ($currentWeighted !== null && $compareWeighted !== null)
            ? $currentWeighted - $compareWeighted
            : null,
    ],
    'checks' => $checks,
    'status' => count($failed) === 0 ? 'PASS' : 'FAIL',
    'failed' => $failed,
    'oracle_writes' => 'NONE',
];

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