<?php

declare(strict_types=1);

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

use App\Repositories\DiarExecutiveOverviewRepository;
use App\Services\DiarReportCatalog;

$result = [
    'result' => 'FAIL',
    'release' => 'DIAR-6B.5-R1.2',
    'sites' => ['MNH', 'NJCH'],
    'month' => '',
    'snapshot_count' => 0,
    'cases' => 0,
    'critical' => 0,
    'high' => 0,
    'medium' => 0,
    'associated_inventory_cost' => 0.0,
    'transactions' => 0,
    'site_case_sum' => 0,
    'site_cost_sum' => 0.0,
    'site_totals_source' => 'SITE_CARD_HEADER',
    'site_totals' => [],
    'approved_sheet_count' => count(DiarReportCatalog::sheets()),
    'approved_workbook_sha256' => DiarReportCatalog::APPROVED_WORKBOOK_SHA256,
    'checks' => [],
];

try {
    $overview = (new DiarExecutiveOverviewRepository())->overview(['MNH', 'NJCH'], [
        'site' => 'ALL',
        'period' => 'latest_closed',
        'month' => '',
    ]);
    $summary = (array)($overview['summary'] ?? []);
    $siteCards = (array)($overview['site_cards'] ?? []);
    $snapshotRefs = (array)($overview['snapshot_refs'] ?? []);

    $siteCaseSum = 0;
    $siteCostCents = 0;
    $siteCodes = [];
    $siteTotals = [];

    foreach ($siteCards as $siteKey => $card) {
        if (!is_array($card) || strtoupper((string)($card['status_code'] ?? '')) !== 'AVAILABLE') {
            continue;
        }

        $header = (array)($card['header'] ?? []);
        $siteCode = strtoupper(trim((string)($card['site_code'] ?? $card['hospital_code'] ?? $siteKey)));
        if ($siteCode === '') {
            continue;
        }

        $siteCases = (int)($header['detected_count'] ?? 0);
        $siteCost = round((float)($header['inventory_cost_abs'] ?? 0), 2);
        $siteCodes[] = $siteCode;
        $siteCaseSum += $siteCases;
        $siteCostCents += (int)round($siteCost * 100);
        $siteTotals[$siteCode] = [
            'cases' => $siteCases,
            'associated_inventory_cost' => $siteCost,
            'snapshot_id' => (int)($header['month_snapshot_id'] ?? 0),
            'snapshot_status' => (string)($header['status_code'] ?? ''),
            'source_db' => (string)($card['source_db'] ?? ''),
        ];
    }

    $summaryCostCents = (int)round((float)($summary['inventory_cost_abs'] ?? 0) * 100);

    $result['month'] = (string)($overview['selected_month'] ?? '');
    $result['snapshot_count'] = count($snapshotRefs);
    $result['cases'] = (int)($summary['detected_count'] ?? 0);
    $result['critical'] = (int)($summary['critical_count'] ?? 0);
    $result['high'] = (int)($summary['high_count'] ?? 0);
    $result['medium'] = (int)($summary['medium_count'] ?? 0);
    $result['associated_inventory_cost'] = round($summaryCostCents / 100, 2);
    $result['transactions'] = (int)($summary['candidate_txn_count'] ?? 0);
    $result['site_case_sum'] = $siteCaseSum;
    $result['site_cost_sum'] = round($siteCostCents / 100, 2);
    $result['site_totals'] = $siteTotals;

    $exactOrder = [
        'Summary', 'Daily Distribution', 'Critical Cases', 'All Cases',
        'Movement Details', 'Store Analysis', 'Movement Type Analysis',
        'Item Analysis', 'User Associations', 'Statistical Basis',
        'Statistical Comparisons', 'Methodology & Controls',
    ];

    $result['checks'] = [
        'approved_sha' => DiarReportCatalog::APPROVED_WORKBOOK_SHA256 === '7af5da46586983abe8c2e7807d82ad64454b7794f7d6da677ba232da0fd39560',
        'twelve_sheets' => count(DiarReportCatalog::sheets()) === 12,
        'exact_sheet_order' => DiarReportCatalog::exactSheetOrder() === $exactOrder,
        'both_sites_available' => in_array('MNH', (array)($overview['available_sites'] ?? []), true)
            && in_array('NJCH', (array)($overview['available_sites'] ?? []), true),
        'two_snapshots' => count($snapshotRefs) === 2,
        'site_cards_complete' => in_array('MNH', $siteCodes, true) && in_array('NJCH', $siteCodes, true),
        'case_total_matches_sites' => $result['cases'] === $siteCaseSum,
        'priority_total_matches_cases' => ($result['critical'] + $result['high'] + $result['medium']) === $result['cases'],
        'associated_cost_matches_sites' => $summaryCostCents === $siteCostCents,
        'closed_month_bound' => $result['month'] !== '' && strtoupper((string)($overview['month_status'] ?? '')) === 'CLOSED',
        'trend_complete' => count((array)($overview['trend'] ?? [])) >= 28,
        'bad_stores_zero' => (int)($summary['bad_store_cases'] ?? 0) === 0,
        'read_only_contract' => !empty($overview['contract']['read_only']),
        'no_db_link_contract' => empty($overview['contract']['database_link']),
        'preview_foundation_only' => true,
    ];
    $result['result'] = !in_array(false, $result['checks'], true) ? 'PASS' : 'FAIL';
} catch (Throwable $e) {
    $result['error'] = preg_replace('/\s+/', ' ', $e->getMessage());
}

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