<?php

declare(strict_types=1);

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

use App\Repositories\InpatientDailyRevenueRepository;
use App\Repositories\InpatientDailyRevenueRuleSettingsRepository;
use App\Services\InpatientDailyRevenueService;

$hospitalCode = normalize_hospital_code((string)($argv[1] ?? env('DDB_QA_HOSPITAL', 'njch')));
$started = microtime(true);
$result = [
    'phase' => 'H11.0-P11.1-R1',
    'release' => '11.0.11.2',
    'title' => 'Daily Inpatient Revenue Live Oracle Read-Only Proof',
    'hospital' => $hospitalCode,
    'mode' => 'LIVE_READ_ONLY_SCHEMA_AND_CURRENT_INPATIENT_QUERY',
    'oracle_writes' => 'NONE',
    'status' => 'FAIL',
    'schema_contract' => 'NOT_RUN',
    'live_current_inpatient_query' => 'NOT_RUN',
    'rows_read' => 0,
    'patients_calculated' => 0,
    'configured_payer_presence' => [],
    'icu_rows_read' => 0,
    'elapsed_ms' => 0,
    'message' => '',
];

try {
    $rules = (new InpatientDailyRevenueRuleSettingsRepository($hospitalCode))->load();
    $repository = new InpatientDailyRevenueRepository($hospitalCode);
    $repository->validateOracleContract();
    $result['schema_contract'] = 'PASS';

    $rows = $repository->currentInpatientsWithRevenue();
    $result['live_current_inpatient_query'] = 'PASS';
    $result['rows_read'] = count($rows);

    $report = (new InpatientDailyRevenueService($hospitalCode, $rules))->build($rows);
    $result['patients_calculated'] = count((array)($report['patients'] ?? []));

    $payerIds = [
        'national_payer' => (int)($rules['national_payer']['company_id'] ?? 0),
        'tcs' => (int)($rules['tiered_payers']['tcs']['company_id'] ?? 0),
        'gosi' => (int)($rules['tiered_payers']['gosi']['company_id'] ?? 0),
    ];
    foreach ($payerIds as $name => $payerId) {
        $count = 0;
        foreach ($rows as $row) {
            if ((int)($row['financlassid'] ?? 0) === $payerId) {
                $count++;
            }
        }
        $result['configured_payer_presence'][$name] = [
            'company_id' => $payerId,
            'rows' => $count,
        ];
    }

    $icuTypes = array_map('strtolower', array_map('trim', array_map('strval', (array)($rules['national_payer']['icu_types'] ?? []))));
    foreach ($rows as $row) {
        $type = strtolower(trim((string)($row['nursing_unit_type'] ?? '')));
        if ($type !== '' && in_array($type, $icuTypes, true)) {
            $result['icu_rows_read']++;
        }
    }

    if ($result['patients_calculated'] !== $result['rows_read']) {
        throw new RuntimeException('Calculated patient count does not match the live Oracle row count.');
    }

    $result['status'] = 'PASS';
    $result['message'] = 'Oracle schema contract and live current-inpatient read completed without any Oracle write operation.';
} catch (Throwable $e) {
    $result['status'] = 'FAIL';
    $result['message'] = $e->getMessage();
    $result['exception'] = get_class($e);
}

$result['elapsed_ms'] = (int)round((microtime(true) - $started) * 1000);
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($result['status'] === 'PASS' ? 0 : 1);
