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

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.86',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P9.2',
    'light_kpi_grid' => strpos($view, 'operations91-kpi-grid') !== false,
    'four_operations_kpis' => substr_count($view, "'tone' =>") >= 4,
    'light_summary_card' => strpos($view, 'operations91-summary-card') !== false,
    'dark_hero_removed' => strpos($view, '<section class="operations91-hero">') === false,
    'semantic_positive_green' => strpos($css, '#047857') !== false
        && strpos($css, '.operations91-delta.positive') !== false,
    'semantic_negative_red' => strpos($css, '#c5283d') !== false
        && strpos($css, '.operations91-delta.negative') !== false,
    'cancellation_inverse_semantics' => strpos($view, "\$cancelledDelta > 0 ? 'negative' : 'positive'") !== false,
    'clean_negative_label' => strpos($view, 'number_format(abs($value), 1)') !== false,
    'fair_comparison_preserved' => strpos($view, 'Fair comparison:') !== false,
    'current_ranking_preserved' => strpos($controller, "\$currentOrder = ((float)\$b['current_value']) <=> ((float)\$a['current_value'])") !== false,
    'zero_current_exclusion_preserved' => strpos($view, '$currentDoctorLeaders') !== false
        && strpos($view, '$currentSpecialtyLeaders') !== false,
    'activity_loss_signal_preserved' => strpos($view, '$largestActivityLoss') !== false,
    'single_chart_preserved' => substr_count($view, 'id="operations91_chart"') === 1,
    'decision_agenda_preserved' => strpos($view, 'operations91-agenda') !== false,
    'flow_safe_header_preserved' => strpos($layout, "['operations', 'lab']") !== false,
    'css_cache_busted' => strpos($layout, '11.0.11.86-r45-p9-2-light-summary-semantic-colors') !== false,
    'oracle_writes_none' => ($version['r45_p9_2']['oracle_writes'] ?? '') === 'NONE',
];

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

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

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