<?php

declare(strict_types=1);

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

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

try {
    $repo = new DoctorsRepository($hospital);
    $options = $repo->availableSpecialties(
        $year,
        $compareYear,
        $startMonth,
        $endMonth
    );

    $ids = [];
    $labels = [];
    $invalid = [];
    foreach ($options as $row) {
        $id = trim((string)($row['id'] ?? ''));
        $label = trim((string)($row['label'] ?? ''));
        if ($id === '' || $label === '') {
            $invalid[] = $row;
            continue;
        }
        $ids[] = $id;
        $labels[] = $label;
    }

    $checks = [
        'options_present' => count($options) > 0,
        'identities_complete' => $invalid === [],
        'ids_unique' => count($ids) === count(array_unique($ids)),
        'labels_present' => count($labels) === count($options),
        'doctor_counts_non_negative' => array_reduce(
            $options,
            static function (bool $ok, array $row): bool {
                return $ok && (int)($row['doctor_count'] ?? -1) >= 0;
            },
            true
        ),
    ];

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

    $result = [
        'schema' => 'DDB_DOCTORS_SPECIALTY_DISCOVERY_V1_1',
        'captured_at' => date(DATE_ATOM),
        'hospital' => strtoupper($hospital),
        'year' => $year,
        'compare_year' => $compareYear,
        'start_month' => $startMonth,
        'end_month' => $endMonth,
        'comparison_contract' => $contract,
        'option_count' => count($options),
        'sample' => array_slice($options, 0, 5),
        '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_DOCTORS_SPECIALTY_DISCOVERY_V1_1',
        '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/doctors';
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
    throw new RuntimeException('Cannot create Doctors evidence directory.');
}
$file = $dir
    . '/DOCTORS_R45_P13_0_1_SPECIALTY_DISCOVERY_'
    . 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);
