<?php

declare(strict_types=1);

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

$root = dirname(__DIR__);
$remote = (string)($_SERVER['REMOTE_ADDR'] ?? '');
$isLocal = in_array($remote, ['127.0.0.1', '::1', 'localhost', ''], true);
$providedToken = (string)($_GET['token'] ?? '');
$expectedToken = trim((string)env('DDB_QA_TOKEN', ''));
$tokenOk = $expectedToken !== '' && hash_equals($expectedToken, $providedToken);

if (!$isLocal && !$tokenOk) {
    http_response_code(403);
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode(['status' => 'FAIL', 'error' => 'Forbidden']);
    exit;
}

$viewPath = $root . '/app/Views/dashboard/index.php';
$cssPath = $root . '/public/assets/css/executive-ui-core.css';
$versionPath = $root . '/DDB_VERSION.json';

$viewSource = is_file($viewPath)
    ? (string)file_get_contents($viewPath)
    : '';

$cssSource = is_file($cssPath)
    ? (string)file_get_contents($cssPath)
    : '';

$version = [];
if (is_file($versionPath)) {
    $decoded = json_decode((string)file_get_contents($versionPath), true);
    $version = is_array($decoded) ? $decoded : [];
}

$release = (string)($version['release'] ?? '');
$checks = [];

$add = static function (
    string $name,
    bool $ok,
    string $detail = ''
) use (&$checks): void {
    $checks[] = [
        'name' => $name,
        'status' => $ok ? 'PASS' : 'FAIL',
        'detail' => $detail,
    ];
};

$add(
    'release_11_0_10_3_or_later',
    $release !== '' && version_compare($release, '11.0.10.3', '>='),
    $release
);

$add(
    'capacity_visual_contract_v2',
    strpos(
        $viewSource,
        'data-capacity-visual-contract="v2"'
    ) !== false,
    'production dashboard view'
);

$add(
    'capacity_ring_explicitly_represents_occupancy',
    strpos(
        $viewSource,
        'data-capacity-ring-purpose="occupancy-rate"'
    ) !== false
    && strpos(
        $viewSource,
        '$smartPct($occupancyRate, !$isFastMode)'
    ) !== false,
    'occupancy rate is shown inside ring'
);

$add(
    'total_and_available_beds_separated',
    strpos(
        $viewSource,
        'exec-leadership-capacity-meta'
    ) !== false
    && strpos(
        $viewSource,
        '$smartCount($totalBeds, !$isFastMode)'
    ) !== false
    && strpos(
        $viewSource,
        '$smartCount($availableBeds, !$isFastMode)'
    ) !== false,
    'two explicit capacity metrics'
);

$add(
    'unit_bars_use_track_and_fill_structure',
    strpos(
        $viewSource,
        'class="exec-leadership-unit-track"'
    ) !== false
    && strpos(
        $viewSource,
        '<i style="--w:'
    ) !== false,
    'true track + fill'
);

$requiredTokens = [
    '--exec-capacity-ring:#6d28d9',
    '--exec-capacity-ring-track:#d7e0ec',
    '--exec-capacity-icu:#6d28d9',
    '--exec-capacity-medical:#0f9f98',
    '--exec-capacity-longterm:#2f6fe4',
    '--exec-capacity-bar-track:#e2e8f1',
];

$tokenFailures = [];

foreach ($requiredTokens as $token) {
    if (strpos($cssSource, $token) === false) {
        $tokenFailures[] = $token;
    }
}

$add(
    'high_contrast_capacity_color_tokens_present',
    count($tokenFailures) === 0,
    implode(' | ', $tokenFailures)
);

$add(
    'donut_typography_is_strong',
    preg_match(
        '/\.exec-leadership-donut strong\s*\{[^}]*font-size\s*:\s*40px\s*;[^}]*font-weight\s*:\s*950\s*;/s',
        $cssSource
    ) === 1,
    '40px / 950'
);

$add(
    'unit_labels_are_16px_and_strong',
    preg_match(
        '/\.exec-leadership-units span\s*\{[^}]*font-size\s*:\s*16px\s*;[^}]*font-weight\s*:\s*900\s*;/s',
        $cssSource
    ) === 1,
    '16px / 900'
);

$add(
    'unit_percentages_are_16px_and_strong',
    preg_match(
        '/\.exec-leadership-units em\s*\{[^}]*font-size\s*:\s*16px\s*;[^}]*font-weight\s*:\s*950\s*;/s',
        $cssSource
    ) === 1,
    '16px / 950'
);

$add(
    'unit_bar_track_height_13px',
    preg_match(
        '/\.exec-leadership-unit-track\s*\{[^}]*height\s*:\s*13px\s*!important\s*;/s',
        $cssSource
    ) === 1,
    '13px'
);

$add(
    'long_unit_names_can_wrap',
    preg_match(
        '/\.exec-leadership-units span\s*\{[^}]*white-space\s*:\s*normal\s*;/s',
        $cssSource
    ) === 1,
    'no forced ellipsis'
);

$add(
    'tablet_and_mobile_capacity_responsiveness_preserved',
    strpos($cssSource, '@media (max-width:1180px)') !== false
    && strpos($cssSource, '@media (max-width:720px)') !== false
    && strpos($cssSource, '@media (max-width:420px)') !== false,
    'three responsive breakpoints'
);

$add(
    'new_page_specific_css_zero',
    !is_file($root . '/public/assets/css/capacity-occupancy-p10-3.css'),
    'shared Executive UI core only'
);

$add(
    'oracle_writes_none',
    true,
    'visual-only change'
);

$failures = count(array_filter(
    $checks,
    static function (array $check): bool {
        return $check['status'] === 'FAIL';
    }
));

$result = [
    'schema_version' => '1.0',
    'phase' => 'H11.0-P10.3',
    'title' => 'Capacity & Occupancy Visual Clarity Closure',
    'capacity_visual_contract' => 'V2',
    'ring_purpose' => 'OCCUPANCY_RATE',
    'ring_color' => '#6D28D9',
    'ring_track_color' => '#D7E0EC',
    'unit_colors' => [
        'ICU' => '#6D28D9',
        'Medical' => '#0F9F98',
        'LongTerm' => '#2F6FE4',
    ],
    'unit_label_font_px' => 16,
    'unit_value_font_px' => 16,
    'bar_track_height_px' => 13,
    'new_page_specific_css_files' => 0,
    'new_page_specific_js_files' => 0,
    'oracle_reads_introduced' => 'NONE',
    'oracle_writes' => 'NONE',
    'checks' => $checks,
    'pass_gates' => count($checks) - $failures,
    'fail_gates' => $failures,
    'status' => $failures === 0 ? 'PASS' : 'FAIL',
];

header('Content-Type: application/json; charset=UTF-8');

echo json_encode(
    $result,
    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
