<?php

declare(strict_types=1);

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

use App\Repositories\DiarExecutiveOverviewRepository;

$options = getopt('', ['site::', 'month::', 'period::', 'expected-cases::', 'expected-snapshot::']);
$site = strtoupper(trim((string)($options['site'] ?? 'MNH')));
$month = trim((string)($options['month'] ?? ''));
$period = strtolower(trim((string)($options['period'] ?? 'latest_closed')));
$expectedCases = isset($options['expected-cases']) ? (int)$options['expected-cases'] : null;
$expectedSnapshot = isset($options['expected-snapshot']) ? (int)$options['expected-snapshot'] : null;

try {
    $data = (new DiarExecutiveOverviewRepository())->overview([$site], [
        'site' => $site,
        'month' => $month,
        'period' => $period,
    ]);
    $card = (array)($data['site_cards'][$site] ?? []);
    $header = (array)($card['header'] ?? []);
    $summary = (array)($data['summary'] ?? []);

    $checks = [
        'source_available' => (string)($card['status_code'] ?? '') === 'AVAILABLE',
        'snapshot_bound' => (int)($header['month_snapshot_id'] ?? 0) > 0,
        'identity_bound' => strpos((string)($card['identity_key'] ?? ''), $site . '|') === 0,
        'bad_stores_zero' => (int)($summary['bad_store_cases'] ?? -1) === 0,
        'missing_days_zero_for_closed' => (string)($header['status_code'] ?? '') !== 'CLOSED' || (int)($header['missing_days'] ?? -1) === 0,
        'read_only_contract' => !empty($data['contract']['read_only']),
        'no_db_link_contract' => array_key_exists('database_link', (array)($data['contract'] ?? [])) && $data['contract']['database_link'] === false,
    ];
    if ($expectedCases !== null) {
        $checks['expected_cases'] = (int)($summary['detected_count'] ?? -1) === $expectedCases;
    }
    if ($expectedSnapshot !== null) {
        $checks['expected_snapshot'] = (int)($header['month_snapshot_id'] ?? -1) === $expectedSnapshot;
    }
    $failed = array_keys(array_filter($checks, static function ($value): bool { return !$value; }));
    if ($failed !== []) {
        throw new RuntimeException('LIVE_CHECK_FAILED:' . implode(',', $failed));
    }

    echo json_encode([
        'result' => 'PASS',
        'release' => 'DIAR-6B.1-R1.1-COMPAT',
        'site' => $site,
        'source_db' => $card['source_db'] ?? null,
        'month' => $data['selected_month'] ?? null,
        'snapshot_id' => $header['month_snapshot_id'] ?? null,
        'version_no' => $header['version_no'] ?? null,
        'status' => $header['status_code'] ?? null,
        'cases' => $summary['detected_count'] ?? null,
        'critical' => $summary['critical_count'] ?? null,
        'high' => $summary['high_count'] ?? null,
        'medium' => $summary['medium_count'] ?? null,
        'bad_stores' => $summary['bad_store_cases'] ?? null,
        'checks' => $checks,
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL;
} catch (Throwable $e) {
    fwrite(STDERR, json_encode([
        'result' => 'FAIL',
        'release' => 'DIAR-6B.1-R1.1-COMPAT',
        'site' => $site,
        'error' => $e->getMessage(),
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL);
    exit(1);
}
