<?php

declare(strict_types=1);

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

use App\Services\RevenueConsolidatedProfiler;

$options = getopt('', ['hospital::', 'year::', 'compare-year::', 'iterations::', 'from-date::', 'to-date::', 'output::']);
$hospital = strtolower((string)($options['hospital'] ?? 'njch'));
$year = (int)($options['year'] ?? date('Y'));
$compareYear = (int)($options['compare-year'] ?? ($year - 1));
$iterations = (int)($options['iterations'] ?? 3);
$fromDate = isset($options['from-date']) && $options['from-date'] !== '' ? (string)$options['from-date'] : null;
$toDate = isset($options['to-date']) && $options['to-date'] !== '' ? (string)$options['to-date'] : null;
$output = (string)($options['output'] ?? (dirname(__DIR__) . '/_qa_evidence/REVENUE_CONSOLIDATED_' . strtoupper($hospital) . '_' . date('Ymd_His')));

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

$result = (new RevenueConsolidatedProfiler($hospital))->profile($year, $compareYear, $iterations, $fromDate, $toDate);
file_put_contents($output . '/REVENUE_CONSOLIDATED_PERFORMANCE.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

$csv = fopen($output . '/REVENUE_CONSOLIDATED_PERFORMANCE.csv', 'wb');
fputcsv($csv, ['Path', 'Query calls', 'Min ms', 'Avg ms', 'Max ms']);
foreach ([
    ['Legacy four-query path', 4, $result['legacy_four_query_path']],
    ['Consolidated one-query path', 1, $result['consolidated_one_query_path']],
] as $line) {
    fputcsv($csv, [$line[0], $line[1], $line[2]['min_ms'], $line[2]['avg_ms'], $line[2]['max_ms']]);
}
fclose($csv);

echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL;
exit($result['status'] === 'PASS' ? 0 : 1);
