<?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 keyed(array $rows, string $key): array
{
    $map = [];
    foreach ($rows as $row) {
        $value = (string)($row[$key] ?? '');
        if ($value !== '') $map[$value] = $row;
    }
    return $map;
}

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

$currentMap = keyed($currentUnits, 'unit_id');
$compareMap = keyed($compareUnits, 'unit_id');
$matchedUnitIds = array_values(array_intersect(array_keys($currentMap), array_keys($compareMap)));

$movementCount = 0;
foreach ($matchedUnitIds as $unitId) {
    $currentValue = (float)($currentMap[$unitId]['bed_efficiency_percentage'] ?? 0);
    $compareValue = (float)($compareMap[$unitId]['bed_efficiency_percentage'] ?? 0);
    if (abs($currentValue - $compareValue) >= 0.05) $movementCount++;
}

$selectedUnitId = (int)($matchedUnitIds[0] ?? 0);
$currentBeds = $selectedUnitId > 0
    ? $repo->legacyCompatibleBedEfficiencyRows($year, $selectedUnitId, $currentFrom, $currentTo)
    : [];
$compareBeds = $selectedUnitId > 0
    ? $repo->legacyCompatibleBedEfficiencyRows($compareYear, $selectedUnitId, $compareFrom, $compareTo)
    : [];

$currentBedMap = keyed($currentBeds, 'bed_name');
$compareBedMap = keyed($compareBeds, 'bed_name');
$matchedBeds = array_values(array_intersect(array_keys($currentBedMap), array_keys($compareBedMap)));

$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_exact' => $currentFrom === '2026-01-01' && $currentTo === '2026-06-30',
    'compare_period_exact' => $compareFrom === '2025-01-01' && $compareTo === '2025-06-30',
    'current_units_present' => count($currentUnits) > 0,
    'compare_units_present' => count($compareUnits) > 0,
    'matched_units_present' => count($matchedUnitIds) > 0,
    'unit_movements_calculable' => $movementCount > 0,
    'weighted_current_available' => $currentWeighted !== null,
    'weighted_compare_available' => $compareWeighted !== null,
    'selected_unit_available' => $selectedUnitId > 0,
    'current_beds_present' => count($currentBeds) > 0,
    'compare_beds_present' => count($compareBeds) > 0,
    'matched_beds_present' => count($matchedBeds) > 0,
];

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

$result = [
    'schema' => 'DDB_BEDS_R45_P8_2_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,
    ],
    'comparison_metrics' => [
        'current_unit_count' => count($currentUnits),
        'compare_unit_count' => count($compareUnits),
        'matched_unit_count' => count($matchedUnitIds),
        'unit_movement_count' => $movementCount,
        'current_weighted_utilization' => $currentWeighted,
        'compare_weighted_utilization' => $compareWeighted,
        'overall_movement_pp' => ($currentWeighted !== null && $compareWeighted !== null)
            ? $currentWeighted - $compareWeighted
            : null,
        'selected_unit_id' => $selectedUnitId,
        'current_bed_count' => count($currentBeds),
        'compare_bed_count' => count($compareBeds),
        'matched_bed_count' => count($matchedBeds),
    ],
    '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_2_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);
