<?php

declare(strict_types=1);

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

use App\Repositories\SpecialtyFinanceRepository;
use App\Services\FairYearComparisonPolicy;
use App\Services\SpecialtyFinanceActivityParityService;

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

try {
    $parity = (new SpecialtyFinanceActivityParityService($hospital))->run(
        $year,
        $compareYear,
        $startMonth,
        $endMonth
    );

    $repo = new SpecialtyFinanceRepository($hospital);
    $periodRows = $repo->specialtyActivityComparison(
        $year,
        $compareYear,
        $startMonth,
        $endMonth
    );
    $monthlyRows = $repo->specialtyActivityMonthlyComparison(
        $year,
        $compareYear,
        $startMonth,
        $endMonth
    );

    $totals = [
        'current_outpatient_visits' => 0.0,
        'compare_outpatient_visits' => 0.0,
        'current_admissions' => 0.0,
        'compare_admissions' => 0.0,
    ];
    $identitiesReady = true;

    foreach ($periodRows as $row) {
        if (
            trim((string)($row['id'] ?? '')) === ''
            || trim((string)($row['label'] ?? '')) === ''
        ) {
            $identitiesReady = false;
        }

        foreach (array_keys($totals) as $metric) {
            $totals[$metric] += (float)($row[$metric] ?? 0);
        }
    }

    $monthlyInRange = $monthlyRows !== [];
    foreach ($monthlyRows as $row) {
        $month = (int)($row['month_id'] ?? 0);
        if ($month < $startMonth || $month > $endMonth) {
            $monthlyInRange = false;
            break;
        }
    }

    $parityCurrent = (array)(
        $parity['reconciliation']['current']['specialty_totals'] ?? []
    );
    $parityCompare = (array)(
        $parity['reconciliation']['compare']['specialty_totals'] ?? []
    );

    $checks = [
        'underlying_parity_pass' => ($parity['status'] ?? 'FAIL') === 'PASS',
        'specialty_rows_present' => count($periodRows) > 0,
        'monthly_rows_present' => count($monthlyRows) > 0,
        'specialty_identities_ready' => $identitiesReady,
        'monthly_rows_within_fair_period' => $monthlyInRange,
        'current_outpatient_total_matches_parity' =>
            $totals['current_outpatient_visits']
            === (float)($parityCurrent['outpatient_visits'] ?? -1),
        'compare_outpatient_total_matches_parity' =>
            $totals['compare_outpatient_visits']
            === (float)($parityCompare['outpatient_visits'] ?? -1),
        'current_admissions_total_matches_parity' =>
            $totals['current_admissions']
            === (float)($parityCurrent['admissions'] ?? -1),
        'compare_admissions_total_matches_parity' =>
            $totals['compare_admissions']
            === (float)($parityCompare['admissions'] ?? -1),
        'both_activity_metrics_present' =>
            $totals['current_outpatient_visits'] > 0
            && $totals['compare_outpatient_visits'] > 0
            && $totals['current_admissions'] > 0
            && $totals['compare_admissions'] > 0,
    ];

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

    $result = [
        'schema' => 'DDB_SPECIALTY_FINANCE_P12_1_LIVE_ACCEPTANCE',
        'captured_at' => date(DATE_ATOM),
        'hospital' => strtoupper($hospital),
        'year' => $year,
        'compare_year' => $compareYear,
        'start_month' => $startMonth,
        'end_month' => $endMonth,
        'comparison_contract' => $contract,
        'counts' => [
            'specialties' => count($periodRows),
            'monthly_rows' => count($monthlyRows),
        ],
        'totals' => $totals,
        'underlying_parity_status' => $parity['status'] ?? 'FAIL',
        'checks' => $checks,
        'failed' => $failed,
        'status' => $failed === [] ? 'PASS' : 'FAIL',
        'oracle_writes' => 'NONE',
    ];
} catch (Throwable $error) {
    $message = preg_replace(
        '/password=[^;\s]+/i',
        'password=[redacted]',
        $error->getMessage()
    );
    $message = preg_replace('/\s+/', ' ', (string)$message);

    $result = [
        'schema' => 'DDB_SPECIALTY_FINANCE_P12_1_LIVE_ACCEPTANCE',
        'captured_at' => date(DATE_ATOM),
        'hospital' => strtoupper($hospital),
        'year' => $year,
        'compare_year' => $compareYear,
        'status' => 'FAIL',
        'failed' => ['live_execution'],
        'error' => trim((string)$message),
        '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 Specialty Finance evidence directory.');
}

$file = $dir
    . '/SPECIALTY_FINANCE_R45_P12_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(($result['status'] ?? 'FAIL') === 'PASS' ? 0 : 1);
