<?php

declare(strict_types=1);

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

use App\Repositories\ExecutiveSummaryRepository;

header('Content-Type: text/plain; charset=utf-8');

$hospital = strtolower((string)($_GET['hospital'] ?? 'njch'));
$repo = new ExecutiveSummaryRepository($hospital);

try {
    $summary = $repo->latestForToday();
    $op = $repo->operationalDayInfo();

    echo "Executive Summary Refresh Status\n";
    echo "Hospital: " . strtoupper($hospital) . "\n";
    echo "Mode: " . (string)env('EXECUTIVE_DASHBOARD_MODE', 'summary') . "\n";
    echo "Max age minutes: " . (string)env('EXECUTIVE_SUMMARY_MAX_AGE_MINUTES', '180') . "\n";
    echo "Refresh hospitals: " . (string)env('EXECUTIVE_REFRESH_HOSPITALS', 'njch') . "\n";
    echo "Operational day start hour: " . (string)($op['start_hour'] ?? '-') . "\n";
    echo "Operational date: " . (string)($op['operational_date'] ?? '-') . "\n";
    echo "Operational window: " . (string)($op['window_start'] ?? '-') . " -> " . (string)($op['window_end'] ?? '-') . "\n";
    echo "Night rollover: " . (!empty($op['is_rollover']) ? 'YES' : 'NO') . "\n\n";

    if (!$summary) {
        echo "Status: NO SUMMARY ROWS FOR OPERATIONAL DAY\n";
        echo "Action: run executive-summary-refresh.php?force=1 after installing Phase 10.3.5.\n";
        exit;
    }

    echo "Status: " . (!empty($summary['is_stale']) ? 'STALE' : 'FRESH') . "\n";
    echo "Last updated: " . ($summary['last_updated'] ?? '-') . "\n";
    echo "Rows: " . count((array)($summary['rows'] ?? [])) . "\n\n";

    $logFile = storage_path('logs/executive-summary-refresh-latest.log');
    echo "Latest scheduler log: " . $logFile . "\n";
    if (is_file($logFile)) {
        echo "---- log tail ----\n";
        $lines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
        foreach (array_slice($lines, -20) as $line) {
            echo $line . "\n";
        }
    } else {
        echo "No scheduler log found yet.\n";
    }
} catch (Throwable $e) {
    http_response_code(500);
    echo "ERROR: " . $e->getMessage() . "\n";
}
