<?php

declare(strict_types=1);

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

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

$result = [
    'result' => 'FAIL',
    'release' => 'DIAR-6B.2-R3.1',
    'site' => 'MNH',
    'source_db' => 'ORAMNH',
    'month' => '2026-06',
    'snapshot_id' => 0,
    'cases' => 0,
    'critical' => 0,
    'high' => 0,
    'medium' => 0,
    'associated_inventory_cost' => 0.0,
    'trend_days' => 0,
    'top_store_rows' => 0,
    'top_item_rows' => 0,
    'first_page_rows' => 0,
    'module_count' => count(DiarWorkspaceNavigation::definitions()),
    'access_matrix_role_count' => count(DiarWorkspaceNavigation::accessMatrixRoles()),
    'role_template_count' => count(DiarWorkspaceNavigation::roleTemplates()),
    'report_sheet_count' => count(DiarWorkspaceNavigation::reportSheets()),
    'checks' => [],
];

try {
    $overview = (new DiarExecutiveOverviewRepository())->overview(['MNH'], [
        'site' => 'MNH',
        'period' => 'latest_closed',
        'month' => '2026-06',
    ]);
    $summary = (array)($overview['summary'] ?? []);
    $snapshotRefs = (array)($overview['snapshot_refs'] ?? []);
    $firstSnapshot = is_array($snapshotRefs[0] ?? null) ? $snapshotRefs[0] : [];

    $filters = [
        'site' => 'MNH', 'month' => '2026-06', 'q' => '', 'severity' => '',
        'branch' => '', 'store' => '', 'item' => '', 'unit' => '',
        'trans_code' => '', 'trans_effect' => '', 'date_from' => '',
        'date_to' => '', 'min_score' => '', 'sort' => 'priority',
    ];
    $cases = (new DiarCasesRepository())->search(['MNH'], $filters, 1, 25);

    $result['snapshot_id'] = (int)($firstSnapshot['month_snapshot_id'] ?? 0);
    $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((float)($summary['inventory_cost_abs'] ?? 0), 2);
    $result['trend_days'] = count((array)($overview['trend'] ?? []));
    $result['top_store_rows'] = count((array)($overview['top_stores'] ?? []));
    $result['top_item_rows'] = count((array)($overview['top_items'] ?? []));
    $result['first_page_rows'] = count((array)($cases['rows'] ?? []));

    $result['checks'] = [
        'six_modules' => $result['module_count'] === 6,
        'seven_access_matrix_roles' => $result['access_matrix_role_count'] === 7,
        'six_role_templates' => $result['role_template_count'] === 6,
        'twelve_report_sheets' => $result['report_sheet_count'] === 12,
        'source_available' => in_array('MNH', (array)($overview['available_sites'] ?? []), true),
        'identity_bound' => (string)($firstSnapshot['source_db'] ?? '') === 'ORAMNH',
        'snapshot_bound' => $result['snapshot_id'] === 2,
        'case_total' => $result['cases'] === 609,
        'critical_total' => $result['critical'] === 141,
        'high_total' => $result['high'] === 358,
        'medium_total' => $result['medium'] === 110,
        'associated_cost' => abs($result['associated_inventory_cost'] - 353429.10) < 0.01,
        'trend_complete' => $result['trend_days'] === 30,
        'rankings_available' => $result['top_store_rows'] >= 5 && $result['top_item_rows'] >= 5,
        'pagination' => $result['first_page_rows'] === 25,
        'bad_stores_zero' => (int)($summary['bad_store_cases'] ?? 0) === 0,
        'read_only_contract' => !empty($overview['contract']['read_only']) && !empty($cases['contract']['read_only']),
        'no_db_link_contract' => empty($overview['contract']['database_link']) && empty($cases['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);
