<?php
$root = dirname(__DIR__);
$version = json_decode(file_get_contents($root . '/DDB_VERSION.json'), true);
$controller = file_get_contents($root . '/app/Controllers/OperationsController.php');
$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');
$js = file_get_contents($root . '/public/assets/js/operations-comparison.js');
$accept = file_get_contents($root . '/tools/operations-r45-p9-live-acceptance.php');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.82',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P9',
    'fair_policy_operations' => strpos($controller, "\$operationsComparisonContract = (new FairYearComparisonPolicy())->resolve") !== false,
    'contract_passed_to_builder' => strpos($controller, '$operationsComparisonContract') !== false,
    'fair_range_applied' => strpos($controller, '$rangeFrom = isset($comparisonContract[\'from_date\'])') !== false,
    'monthly_rows_filtered' => substr_count($controller, '$this->filterMonthlyRows(') >= 6,
    'matched_rank_comparison' => strpos($controller, 'mergeOperationRankComparisons') !== false,
    'current_and_compare_specialties' => strpos($controller, 'Current operation specialties') !== false
        && strpos($controller, 'Comparison operation specialties') !== false,
    'executive_controls' => strpos($view, 'operations91-controls') !== false,
    'single_executive_hero' => strpos($view, 'operations91-hero') !== false,
    'one_main_chart_canvas' => substr_count($view, 'id="operations91_chart"') === 1,
    'decision_agenda' => strpos($view, 'operations91-agenda') !== false,
    'concentration_comparison' => strpos($view, 'specialtyComparisons') !== false
        && strpos($view, 'doctorComparisons') !== false,
    'details_collapsed' => strpos($view, '<details class="operations91-details"') !== false,
    'old_r37_shell_removed' => strpos($view, 'operations137-shell') === false,
    'css_loaded' => strpos($layout, 'operations-executive-redesign.css?v=11.0.11.82-r45-p9-fair-executive') !== false,
    'js_loaded' => strpos($layout, 'operations-comparison.js?v=11.0.11.82-r45-p9-fair-executive') !== false,
    'single_chart_js' => strpos($js, "renderBarCompareChart('operations91_chart'") !== false,
    'responsive_css' => strpos($css, '@media(max-width:760px)') !== false,
    'live_acceptance' => strpos($accept, 'DDB_OPERATIONS_R45_P9_LIVE_ACCEPTANCE_V1') !== false,
    'oracle_writes_none' => ($version['r45_p9']['oracle_writes'] ?? '') === 'NONE',
];

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

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

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