<?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');
$layout = file_get_contents($root . '/app/Views/layouts/main.php');
$css = file_get_contents($root . '/public/assets/css/beds-executive-redesign.css');
$controller = file_get_contents($root . '/app/Controllers/BedsController.php');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.87',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P8.4',
    'light_kpi_grid' => strpos($view, 'beds84-kpi-grid') !== false,
    'four_beds_kpis' => substr_count($view, "'tone' =>") >= 4,
    'light_summary_card' => strpos($view, 'beds84-summary-card') !== false,
    'dark_hero_removed' => strpos($view, '<section class="beds83-hero">') === false,
    'semantic_positive_green' => strpos($css, '#047857') !== false
        && strpos($css, '.beds84-delta.positive') !== false,
    'semantic_negative_red' => strpos($css, '#c5283d') !== false
        && strpos($css, '.beds84-delta.negative') !== false,
    'clean_negative_movement' => strpos($view, 'number_format(abs($value), 1)') !== false,
    'all_units_default_preserved' => strpos($view, "value=\"0\" <?= \$isAllUnits ? 'selected' : '' ?>") !== false,
    'unit_specific_scope_preserved' => strpos($view, '$selectedUnitMovement') !== false
        && strpos($view, '$selectedUnitName') !== false,
    'live_independence_preserved' => strpos($view, 'independent of selected years') !== false,
    'fair_comparison_preserved' => strpos($view, 'Fair comparison:') !== false,
    'unit_chart_preserved' => strpos($view, 'id="beds82_units_chart"') !== false,
    'bed_chart_preserved' => strpos($view, 'id="beds82_beds_chart"') !== false,
    'decision_agenda_preserved' => strpos($view, 'beds83-agenda') !== false,
    'details_collapsed_preserved' => strpos($view, '<details class="beds83-details"') !== false,
    'flow_safe_header' => strpos($layout, "['operations', 'lab', 'beds']") !== false,
    'css_cache_busted' => strpos($layout, '11.0.11.87-r45-p8-4-light-summary-semantic-colors') !== false,
    'controller_untouched_comparison_contract' => strpos($controller, 'FairYearComparisonPolicy') !== false,
    'oracle_writes_none' => ($version['r45_p8_4']['oracle_writes'] ?? '') === 'NONE',
];

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

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

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