<?php

declare(strict_types=1);

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

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 {
    $result = (new SpecialtyFinanceActivityParityService($hospital))->run(
        $year,
        $compareYear,
        $startMonth,
        $endMonth
    );
    $result['comparison_contract'] = $contract;
} catch (Throwable $error) {
    $message = preg_replace(
        '/password=[^;\s]+/i',
        'password=[redacted]',
        $error->getMessage()
    );
    $message = preg_replace('/\s+/', ' ', (string)$message);

    $result = [
        'schema' => 'DDB_SPECIALTY_FINANCE_ACTIVITY_PARITY_V1',
        'captured_at' => date(DATE_ATOM),
        'hospital' => strtoupper($hospital),
        'year' => $year,
        'compare_year' => $compareYear,
        'start_month' => $startMonth,
        'end_month' => $endMonth,
        'comparison_contract' => $contract,
        '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_0_ACTIVITY_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);
