<?php

declare(strict_types=1);

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

use App\Services\RevenuePerformanceProfiler;

$args = [];
foreach (array_slice($argv ?? [], 1) as $arg) {
    if (strpos($arg, '--') === 0 && strpos($arg, '=') !== false) {
        [$key, $value] = explode('=', substr($arg, 2), 2);
        $args[$key] = $value;
    }
}

$hospital = strtolower(trim((string)($args['hospital'] ?? 'njch')));
$year = (int)($args['year'] ?? date('Y'));
$compareYear = (int)($args['compare-year'] ?? ($year - 1));
$iterations = max(1, min(5, (int)($args['iterations'] ?? 1)));
$outputDir = trim((string)($args['output'] ?? storage_path('evidence/revenue-r45-p0')));

if (!is_dir($outputDir) && !@mkdir($outputDir, 0775, true) && !is_dir($outputDir)) {
    fwrite(STDERR, "Cannot create output directory: {$outputDir}\n");
    exit(2);
}

try {
    $profiler = new RevenuePerformanceProfiler($hospital);
    $result = $profiler->profile($year, $compareYear, $iterations);
} catch (Throwable $e) {
    $result = [
        'schema_version' => '1.0',
        'phase' => 'H11.0-P11.1-R45-P0',
        'status' => 'UNAVAILABLE',
        'generated_at' => date(DATE_ATOM),
        'hospital' => strtoupper($hospital),
        'year' => $year,
        'compare_year' => $compareYear,
        'error' => $e->getMessage(),
        'write_operations' => 'NONE',
    ];
}

$jsonPath = rtrim($outputDir, '/\\') . DIRECTORY_SEPARATOR . 'REVENUE_PERFORMANCE_BASELINE.json';
$timingsPath = rtrim($outputDir, '/\\') . DIRECTORY_SEPARATOR . 'REVENUE_QUERY_TIMINGS.csv';
$oraclePath = rtrim($outputDir, '/\\') . DIRECTORY_SEPARATOR . 'REVENUE_ORACLE_OBJECT_DIAGNOSTICS.json';
$contractPath = rtrim($outputDir, '/\\') . DIRECTORY_SEPARATOR . 'REVENUE_YEAR_COMPARISON_CONTRACT.json';
$mvPath = rtrim($outputDir, '/\\') . DIRECTORY_SEPARATOR . 'REVENUE_MV_READINESS.json';

file_put_contents($jsonPath, json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
file_put_contents($oraclePath, json_encode($result['oracle_diagnostics'] ?? ['status' => 'UNAVAILABLE'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
file_put_contents($contractPath, json_encode($result['year_comparison_contract'] ?? RevenuePerformanceProfiler::yearComparisonContract($year, $compareYear), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
$oracle = is_array($result['oracle_diagnostics'] ?? null) ? $result['oracle_diagnostics'] : [];
file_put_contents($mvPath, json_encode([
    'phase' => 'H11.0-P11.1-R45-P0',
    'hospital' => strtoupper($hospital),
    'config_enabled' => (bool)($oracle['mv_config_enabled'] ?? false),
    'present' => (bool)($oracle['mv_present'] ?? false),
    'rows' => $oracle['mv'] ?? [],
    'diagnostic_status' => $oracle['status'] ?? 'UNAVAILABLE',
    'errors' => $oracle['errors']['mv'] ?? null,
    'write_operations' => 'NONE',
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));

$fp = fopen($timingsPath, 'wb');
fputcsv($fp, ['query', 'status', 'rows', 'min_ms', 'avg_ms', 'max_ms', 'samples_ms']);
foreach ((array)($result['timings'] ?? []) as $name => $timing) {
    fputcsv($fp, [
        $name,
        $timing['status'] ?? '',
        $timing['rows'] ?? '',
        $timing['min_ms'] ?? '',
        $timing['avg_ms'] ?? '',
        $timing['max_ms'] ?? '',
        implode('|', array_map('strval', (array)($timing['samples_ms'] ?? []))),
    ]);
}
fclose($fp);

$status = (string)($result['status'] ?? (isset($result['error']) ? 'UNAVAILABLE' : 'COMPLETE'));
echo "R45-P0 Revenue Performance Baseline\n";
echo "Hospital     : " . strtoupper($hospital) . "\n";
echo "Years        : {$year} vs {$compareYear}\n";
echo "Iterations   : {$iterations}\n";
echo "Status       : {$status}\n";
echo "Output       : {$outputDir}\n";
echo "Writes       : NONE\n";

exit(in_array($status, ['COMPLETE', 'PARTIAL'], true) ? 0 : 2);
