<?php
declare(strict_types=1);

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

use App\Core\Database;
use App\Repositories\DoctorsRepository;
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 DoctorsRepository($hospital);
$summary = $repo->summary($year, $compareYear, $startMonth, $endMonth);

function refTotal(string $hospital, int $year, string $metric, int $startMonth, int $endMonth): float
{
    $allowed = ['TOT_REV', 'TOTAL_OP_VISITS', 'TOTAL_INPAT_VISITS'];
    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);
}

$mapping = [
    'revenue' => ['TOT_REV', 'current_revenue', 'compare_revenue'],
    'opd' => ['TOTAL_OP_VISITS', 'current_op_visits', 'compare_op_visits'],
    'inpatient' => ['TOTAL_INPAT_VISITS', 'current_inpat_visits', 'compare_inpat_visits'],
];

$checks = [];
foreach ($mapping as $key => $meta) {
    [$metric, $currentKey, $compareKey] = $meta;
    $currentRef = refTotal($hospital, $year, $metric, $startMonth, $endMonth);
    $compareRef = refTotal($hospital, $compareYear, $metric, $startMonth, $endMonth);
    $checks['current_' . $key] = [
        'actual' => (float)$summary[$currentKey],
        'reference' => $currentRef,
        'pass' => abs((float)$summary[$currentKey] - $currentRef) < 0.0001,
    ];
    $checks['compare_' . $key] = [
        'actual' => (float)$summary[$compareKey],
        'reference' => $compareRef,
        'pass' => abs((float)$summary[$compareKey] - $compareRef) < 0.0001,
    ];
}

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

$result = [
    'schema' => 'DDB_DOCTORS_R45_P7_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/doctors';
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
    throw new RuntimeException('Cannot create Doctors evidence directory.');
}
$file = $dir . '/DOCTORS_R45_P7_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);
