<?php

declare(strict_types=1);

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

use App\Services\DiarPrebuiltReportCacheService;

$options = getopt('', ['scope::', 'month::', 'user::']);
$scope = strtoupper(trim((string)($options['scope'] ?? 'ALL_SCOPES')));
$month = trim((string)($options['month'] ?? ''));
$user = trim((string)($options['user'] ?? 'DIAR-NIGHTLY-CACHE'));
$allowed = ['NJCH', 'MNH'];
$service = new DiarPrebuiltReportCacheService();

try {
    if ($scope === 'ALL_SCOPES') {
        $rows = $service->buildAll($allowed, $month, $user);
    } else {
        if (!in_array($scope, ['NJCH', 'MNH', 'ALL'], true)) {
            throw new RuntimeException('INVALID_SCOPE');
        }
        $rows = [$service->build($allowed, [
            'site' => $scope,
            'period' => 'latest_closed',
            'month' => $month,
        ], true, $user)];
    }

    $summary = [];
    foreach ($rows as $row) {
        $manifest = (array)($row['manifest'] ?? []);
        $counts = (array)($manifest['summary'] ?? []);
        $summary[] = [
            'scope' => (string)($manifest['scope_code'] ?? ''),
            'month' => (string)($manifest['selected_month'] ?? ''),
            'prepared_at' => (string)($manifest['prepared_at'] ?? ''),
            'cases' => (int)($counts['cases'] ?? 0),
            'critical' => (int)($counts['critical'] ?? 0),
            'movement_rows' => (int)($counts['movement_rows'] ?? 0),
            'excel_ready' => is_file((string)($row['excel_path'] ?? '')),
            'powerpoint_ready' => is_file((string)($row['powerpoint_path'] ?? '')),
        ];
    }

    echo json_encode([
        'result' => 'PASS',
        'release' => 'DIAR-6B.5-R2.5',
        'builds' => $summary,
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), PHP_EOL;
    echo 'DIAR_6B_5_R2_5_CACHE_BUILD|PASS|SCOPES=' . count($summary) . '|MONTH='
        . ($month !== '' ? $month : 'LATEST') . '|EXPORTS=READY', PHP_EOL;
    exit(0);
} catch (Throwable $e) {
    echo json_encode([
        'result' => 'FAIL',
        'release' => 'DIAR-6B.5-R2.5',
        'error' => preg_replace('/\s+/', ' ', $e->getMessage()),
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), PHP_EOL;
    echo 'DIAR_6B_5_R2_5_CACHE_BUILD|FAIL|ERROR='
        . preg_replace('/[^A-Z0-9_.:-]+/i', '_', $e->getMessage()), PHP_EOL;
    exit(71);
}
