<?php

declare(strict_types=1);

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

use App\Repositories\ExecutiveSummaryRepository;

$isCli = PHP_SAPI === 'cli';
if ($isCli) {
    @set_time_limit(0);
} else {
    @set_time_limit(300);
    header('Content-Type: text/plain; charset=utf-8');
}

$hospital = $isCli ? (string)($argv[1] ?? '') : (string)($_GET['hospital'] ?? '');
$hospital = trim($hospital) !== '' ? strtolower(trim($hospital)) : strtolower((string)env('EXECUTIVE_REFRESH_HOSPITALS', 'njch'));
$token = $isCli ? (string)($argv[2] ?? '') : (string)($_GET['token'] ?? '');
$force = $isCli ? in_array('--force', $argv ?? [], true) : ((string)($_GET['force'] ?? '') === '1');
$expectedToken = trim((string)env('EXECUTIVE_REFRESH_TOKEN', ''));
$lockMinutes = max(5, (int)env('EXECUTIVE_REFRESH_LOCK_MINUTES', '30'));

if (!$isCli && ($expectedToken === '' || !hash_equals($expectedToken, $token))) {
    http_response_code(403);
    echo "Forbidden: set EXECUTIVE_REFRESH_TOKEN in .env and pass ?token=YOUR_TOKEN\n";
    exit;
}

$available = array_keys((array)config('hospitals', []));
$requested = preg_split('/[,;\s]+/', $hospital, -1, PREG_SPLIT_NO_EMPTY) ?: ['njch'];
$targets = [];
foreach ($requested as $item) {
    $item = strtolower(trim((string)$item));
    if ($item === 'all') {
        $targets = array_values(array_unique(array_merge($targets, $available)));
    } elseif ($item !== '') {
        $targets[] = $item;
    }
}
$targets = array_values(array_unique($targets));

$storage = function_exists('storage_path') ? storage_path('logs') : dirname(__DIR__) . '/storage/logs';
$lockDir = function_exists('storage_path') ? storage_path('locks') : dirname(__DIR__) . '/storage/locks';
if (!is_dir($storage)) { @mkdir($storage, 0775, true); }
if (!is_dir($lockDir)) { @mkdir($lockDir, 0775, true); }

$lockKey = preg_replace('/[^a-z0-9_\-]+/i', '_', implode('_', $targets));
$lockFile = $lockDir . '/executive-summary-' . $lockKey . '.lock';

if (!$force && is_file($lockFile) && (time() - (int)@filemtime($lockFile)) < ($lockMinutes * 60)) {
    echo "Executive summary refresh skipped: another refresh appears to be running.\n";
    echo "Lock: {$lockFile}\n";
    echo "Use force=1 in browser, or --force in CLI, only if you are sure the old process finished.\n";
    exit;
}
@file_put_contents($lockFile, getmypid() . ' ' . date('c'));

try {
    $lines = [];
    $results = [];
    foreach ($targets as $target) {
        if (!in_array($target, $available, true)) {
            $results[$target] = ['error' => 'Unknown hospital code'];
            continue;
        }
        $start = microtime(true);
        $repo = new ExecutiveSummaryRepository($target);
        $result = $repo->refreshToday();
        $result['seconds'] = round(microtime(true) - $start, 2);
        $results[$target] = $result;
    }

    $lines[] = "Executive summary refresh completed";
    foreach ($results as $key => $result) {
        if (isset($result['error'])) {
            $lines[] = strtoupper($key) . ": ERROR - " . $result['error'];
        } else {
            $op = is_array($result['operational'] ?? null) ? $result['operational'] : [];
            $opText = '';
            if (!empty($op['operational_date'])) {
                $opText = ' | operational_day=' . $op['operational_date'];
                if (!empty($op['is_rollover'])) { $opText .= ' night_rollover=1'; }
            }
            $lines[] = strtoupper($key)
                . ": inserted " . ($result['inserted'] ?? 0)
                . " KPI rows at " . ($result['updated_at'] ?? '')
                . " in " . ($result['seconds'] ?? '-') . " sec"
                . $opText;
        }
    }
    echo implode(PHP_EOL, $lines) . PHP_EOL;

    $logText = '[' . date('c') . '] ' . implode(' | ', $lines) . PHP_EOL;
    @file_put_contents($storage . '/executive-summary-refresh-latest.log', $logText, FILE_APPEND);
} catch (Throwable $e) {
    http_response_code(500);
    echo "ERROR: " . $e->getMessage() . "\n";
    echo "Details were also logged in storage/logs/app.log\n";
    @error_log('[' . date('c') . '] executive-summary-refresh: ' . $e . PHP_EOL, 3, $storage . '/app.log');
} finally {
    @unlink($lockFile);
}
