<?php

declare(strict_types=1);

$root = dirname(__DIR__);
require_once $root . '/app/bootstrap.php';

use App\Core\Auth;
use App\Core\BranchReadiness;
use App\Core\Session;

$version = json_decode((string)file_get_contents($root . '/DDB_VERSION.json'), true);
$authSource = (string)file_get_contents($root . '/app/Core/Auth.php');
$authControllerSource = (string)file_get_contents($root . '/app/Controllers/AuthController.php');
$layoutSource = (string)file_get_contents($root . '/app/Views/layouts/main.php');
$revenueSource = (string)file_get_contents($root . '/app/Controllers/RevenueController.php');
$helpersSource = (string)file_get_contents($root . '/app/helpers.php');

$hospitals = config('hospitals', []);
$liveHospitals = BranchReadiness::liveHospitals(is_array($hospitals) ? $hospitals : []);
$liveCodes = BranchReadiness::liveCodes();

Session::put('user', [
    'name' => 'QA',
    'hospital' => 'njch',
    'dashboard_role' => 1,
    'dashboard_role_fin' => 1,
    'dashboard_role_revenue' => 1,
]);

$blockedSet = Auth::setHospital('jckh') === false;
$hospitalAfterBlockedSet = Auth::hospital();

$allowedSet = Auth::setHospital('mnh') === true;
$hospitalAfterAllowedSet = Auth::hospital();

Session::put('user', [
    'name' => 'QA',
    'hospital' => 'jckh',
    'dashboard_role' => 1,
    'dashboard_role_fin' => 1,
    'dashboard_role_revenue' => 1,
]);
$recoveredHospital = Auth::hospital();
$recoveredUser = Auth::user();

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.88',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P11.1',
    'njch_live' => BranchReadiness::isLive('njch') === true,
    'mnh_live' => BranchReadiness::isLive('mnh') === true,
    'jckh_not_live' => BranchReadiness::isLive('jckh') === false,
    'unknown_not_live' => BranchReadiness::isLive('unknown') === false,
    'live_codes_exact' => $liveCodes === ['njch', 'mnh'],
    'live_hospitals_excludes_jckh' => array_keys($liveHospitals) === ['njch', 'mnh'],
    'default_hospital_is_live' => BranchReadiness::isLive(default_hospital()),
    'backend_blocks_jckh' => $blockedSet,
    'blocked_set_preserves_ready_context' => $hospitalAfterBlockedSet === 'njch',
    'backend_allows_mnh' => $allowedSet && $hospitalAfterAllowedSet === 'mnh',
    'old_session_auto_recovers' => $recoveredHospital !== 'jckh'
        && BranchReadiness::isLive($recoveredHospital),
    'recovery_persisted' => is_array($recoveredUser)
        && ($recoveredUser['hospital'] ?? '') === $recoveredHospital
        && ($recoveredUser['hospital_recovery_reason'] ?? '') === 'BRANCH_NOT_READY_FOR_LIVE_VIEWS',
    'auth_attempt_guard' => strpos($authSource, 'if (!BranchReadiness::isLive($hospitalCode))') !== false,
    'auth_set_guard' => substr_count($authSource, 'BranchReadiness::isLive($hospitalCode)') >= 2,
    'switch_controller_guard' => strpos($authControllerSource, '!BranchReadiness::isLive($hospital)') !== false,
    'switch_user_message' => strpos($authControllerSource, 'not available until its readiness is completed and approved') !== false,
    'modal_uses_live_hospitals' => strpos($layoutSource, 'foreach ($liveHospitals as $code => $hospital)') !== false,
    'modal_does_not_loop_all_hospitals' => strpos($layoutSource, 'foreach ($hospitals as $code => $hospital)') === false,
    'revenue_backend_guard' => strpos($revenueSource, '!BranchReadiness::isLive($hospitalCode)') !== false,
    'revenue_ui_filtered' => strpos($revenueSource, "'hospitals' => BranchReadiness::liveHospitals") !== false,
    'default_helper_uses_readiness' => strpos($helpersSource, "config('branch_readiness.branches', [])") !== false,
    'permissions_explicitly_deferred' => ($version['r45_p11_1']['permissions_scope'] ?? '') === 'DEFERRED_TO_FUTURE_USER_LEVEL_AUTHORIZATION_SYSTEM',
    'oracle_writes_none' => ($version['r45_p11_1']['oracle_writes'] ?? '') === 'NONE',
];

$failed = [];
foreach ($checks as $name => $passed) {
    if (!$passed) {
        $failed[] = $name;
    }
}

echo json_encode([
    'schema' => 'R45_P11_1_BRANCH_READINESS_QA',
    'policy' => BranchReadiness::policy()['policy'] ?? null,
    'live_codes' => $liveCodes,
    'blocked_codes' => array_values(array_diff(array_keys(is_array($hospitals) ? $hospitals : []), $liveCodes)),
    'checks' => $checks,
    'passed' => count($checks) - count($failed),
    'failed' => $failed,
    'oracle_writes' => 'NONE',
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;

exit($failed === [] ? 0 : 1);
