<?php

declare(strict_types=1);

/**
 * Resolve the active monthly snapshot without assuming snapshot_refs is keyed by site.
 *
 * Priority:
 * 1. site_status[site].snapshot_id — authoritative read-model status.
 * 2. Scan numeric/associative snapshot_refs for matching hospital_code.
 *
 * @param array<string,mixed> $status
 * @param array<mixed> $snapshotRefs
 */
function diarResolveSnapshotId(array $status, array $snapshotRefs, string $site): int
{
    $statusId = (int)($status['snapshot_id'] ?? 0);
    if ($statusId > 0) {
        return $statusId;
    }

    $site = strtoupper(trim($site));
    foreach ($snapshotRefs as $ref) {
        if (!is_array($ref)) {
            continue;
        }
        $refSite = strtoupper(trim((string)($ref['hospital_code'] ?? '')));
        $snapshotId = (int)($ref['month_snapshot_id'] ?? 0);
        if ($refSite === $site && $snapshotId > 0) {
            return $snapshotId;
        }
    }

    return 0;
}

if (defined('DIAR_ACCEPTANCE_RESOLVER_ONLY')) {
    return;
}

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

use App\Repositories\DiarCasesRepository;
use App\Services\DiarWorkspaceNavigation;

$result = [
    'result' => 'FAIL',
    'release' => 'DIAR-6B.2-R2.1.1-ACCEPTANCE-HOTFIX',
    'site' => 'MNH',
    'source_db' => '',
    'month' => '2026-06',
    'snapshot_id' => null,
    'snapshot_resolution' => '',
    'total_cases' => 0,
    'first_page_rows' => 0,
    'module_count' => count(DiarWorkspaceNavigation::definitions()),
    'role_template_count' => count(DiarWorkspaceNavigation::roleTemplates()),
    'report_sheet_count' => count(DiarWorkspaceNavigation::reportSheets()),
    'checks' => [],
];

try {
    $filters = [
        'site' => 'MNH',
        'month' => '2026-06',
        'q' => '',
        'severity' => '',
        'branch' => '',
        'store' => '',
        'item' => '',
        'unit' => '',
        'trans_code' => '',
        'trans_effect' => '',
        'date_from' => '',
        'date_to' => '',
        'min_score' => '',
        'sort' => 'priority',
    ];

    $data = (new DiarCasesRepository())->search(['MNH'], $filters, 1, 25);
    $status = (array)($data['site_status']['MNH'] ?? []);
    $snapshotRefs = (array)($data['snapshot_refs'] ?? []);

    $statusSnapshotId = (int)($status['snapshot_id'] ?? 0);
    $resolvedSnapshotId = diarResolveSnapshotId($status, $snapshotRefs, 'MNH');

    $result['source_db'] = (string)($status['source_db'] ?? '');
    $result['snapshot_id'] = $resolvedSnapshotId;
    $result['snapshot_resolution'] = $statusSnapshotId > 0 ? 'SITE_STATUS' : ($resolvedSnapshotId > 0 ? 'SNAPSHOT_REFS_SCAN' : 'NOT_RESOLVED');
    $result['total_cases'] = (int)($data['total'] ?? 0);
    $result['first_page_rows'] = count((array)($data['rows'] ?? []));

    $result['checks'] = [
        'six_modules' => $result['module_count'] === 6,
        'six_role_templates' => $result['role_template_count'] === 6,
        'twelve_report_sheets' => $result['report_sheet_count'] === 12,
        'source_available' => in_array('MNH', (array)($data['available_sites'] ?? []), true),
        'identity_bound' => $result['source_db'] === 'ORAMNH',
        'snapshot_bound' => $result['snapshot_id'] === 2,
        'snapshot_resolution_valid' => in_array($result['snapshot_resolution'], ['SITE_STATUS', 'SNAPSHOT_REFS_SCAN'], true),
        'case_total' => $result['total_cases'] === 609,
        'pagination' => $result['first_page_rows'] === 25,
        'bad_stores_zero' => (int)($data['summary']['bad_stores'] ?? 0) === 0,
        'read_only_contract' => !empty($data['contract']['read_only']),
        'no_db_link_contract' => empty($data['contract']['database_link']),
    ];

    $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);
