<?php
declare(strict_types=1);

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

use App\Core\Database;
use App\Repositories\SpecialtyFinanceRepository;
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);
$startMonth = (int)($contract['start_month'] ?? 1);
$endMonth = (int)($contract['end_month'] ?? 12);

$repo = new SpecialtyFinanceRepository($hospital);
$summary = $repo->summary($year, $compareYear, $startMonth, $endMonth);

function referenceTotal(string $hospital, int $year, string $metric, int $startMonth, int $endMonth): float
{
    $allowed = ['MOH', 'DRUG_REV', 'NET_REV_AFTER_DRUG_MOH'];
    if (!in_array($metric, $allowed, true)) {
        throw new RuntimeException('Invalid metric');
    }

    $row = Database::fetchOne($hospital, "
        WITH per_doctor AS (
            SELECT EMP_ID doctor_key,
                   NVL(SUM(DISTINCT NVL({$metric}, 0)), 0) metric_value
            FROM KPI_DOCTOR_PERF_DETAIL_JOB
            WHERE YEARID = :year
              AND MONTHID BETWEEN :start_month AND :end_month
            GROUP BY EMP_ID
        )
        SELECT NVL(SUM(metric_value), 0) total_value
        FROM per_doctor
    ", [
        'year' => $year,
        'start_month' => $startMonth,
        'end_month' => $endMonth,
    ]);

    return (float)($row['total_value'] ?? 0);
}

$checks = [];
foreach ([
    'moh' => 'MOH',
    'drug' => 'DRUG_REV',
    'net' => 'NET_REV_AFTER_DRUG_MOH',
] as $key => $metric) {
    foreach (['current' => $year, 'compare' => $compareYear] as $side => $targetYear) {
        $actual = (float)$summary[$side . '_' . $key];
        $reference = referenceTotal($hospital, $targetYear, $metric, $startMonth, $endMonth);
        $checks[$side . '_' . $key] = [
            'actual' => $actual,
            'reference' => $reference,
            'difference' => round($actual - $reference, 6),
            'pass' => abs($actual - $reference) < 0.0001,
        ];
    }
}

$passed = true;
foreach ($checks as $check) {
    if (!$check['pass']) $passed = false;
}

$result = [
    'schema' => 'DDB_SPECIALTY_FINANCE_R45_P6_1_LIVE_ACCEPTANCE_V1',
    'captured_at' => date(DATE_ATOM),
    'hospital' => $hospital,
    'year' => $year,
    'compare_year' => $compareYear,
    'contract' => $contract,
    'expected_period' => ['start_month' => $startMonth, 'end_month' => $endMonth],
    'checks' => $checks,
    'status' => $passed ? 'PASS' : 'FAIL',
    'oracle_writes' => 'NONE',
];

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