<?php
$root = dirname(__DIR__);
$version = json_decode(file_get_contents($root . '/DDB_VERSION.json'), true);
$view = file_get_contents($root . '/app/Views/beds/index.php');
$css = file_get_contents($root . '/public/assets/css/beds-executive-redesign.css');
$layout = file_get_contents($root . '/app/Views/layouts/main.php');
$js = file_get_contents($root . '/public/assets/js/beds-comparison.js');
$controller = file_get_contents($root . '/app/Controllers/BedsController.php');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.80',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P8.3',
    'compact_controls' => strpos($view, 'beds83-controls') !== false,
    'single_executive_hero' => strpos($view, 'beds83-hero') !== false,
    'live_snapshot_inside_hero' => strpos($view, 'beds83-live-strip') !== false,
    'one_main_unit_chart' => substr_count($view, 'id="beds82_units_chart"') === 1,
    'decision_agenda' => strpos($view, 'beds83-agenda') !== false,
    'selected_unit_drilldown' => strpos($view, 'beds83-unit-review') !== false,
    'details_collapsed' => strpos($view, '<details class="beds83-details"') !== false,
    'old_large_results_section_removed' => strpos($view, 'MATCHED PERIOD RESULTS') === false,
    'old_separate_live_section_removed' => strpos($view, 'beds82-live-section') === false,
    'old_comparison_summary_removed' => strpos($view, 'beds82-summary-card') === false,
    'old_priority_section_removed' => strpos($view, 'beds82-priority-card') === false,
    'executive_narrative' => strpos($view, '$executiveNarrative') !== false,
    'isolated_css_loaded' => strpos(
        $layout,
        'beds-executive-redesign.css?v=11.0.11.80-r45-p8-3-executive-redesign'
    ) !== false,
    'js_cache_updated' => strpos(
        $layout,
        'beds-comparison.js?v=11.0.11.80-r45-p8-3-executive-redesign'
    ) !== false,
    'responsive_css' => strpos($css, '@media (max-width: 760px)') !== false,
    'fair_policy_preserved' => strpos($controller, 'FairYearComparisonPolicy') !== false,
    'comparison_chart_preserved' => strpos($js, "name: config.currentLabel") !== false
        && strpos($js, "name: config.compareLabel") !== false,
    'oracle_writes_none' => ($version['r45_p8_3']['oracle_writes'] ?? '') === 'NONE',
];

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

echo json_encode([
    'schema' => 'R45_P8_3_QA',
    'checks' => $checks,
    'passed' => count($checks) - count($failed),
    'failed' => $failed,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;

exit(count($failed) === 0 ? 0 : 1);
