<?php
declare(strict_types=1);

$root = dirname(__DIR__);
$version = json_decode((string)file_get_contents($root . '/DDB_VERSION.json'), true);
$controller = (string)file_get_contents($root . '/app/Controllers/BranchComparisonController.php');
$repo = (string)file_get_contents($root . '/app/Repositories/BranchComparisonRepository.php');
$view = (string)file_get_contents($root . '/app/Views/branch_comparison/index.php');
$css = (string)file_get_contents($root . '/public/assets/css/branch-comparison.css');
$js = (string)file_get_contents($root . '/public/assets/js/branch-comparison.js');
$layout = (string)file_get_contents($root . '/app/Views/layouts/main.php');
$env = (string)file_get_contents($root . '/.env');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.98',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P11.3',
    'service_first_method' => strpos($controller, 'buildServiceFirstAnalysis(') !== false,
    'old_aggregate_method_removed' => strpos($controller, 'buildExecutiveAnalysis(') === false,
    'old_domain_status_method_removed' => strpos($controller, 'domainDecisionStatus(') === false,
    'mixed_branch_accumulation_removed' => strpos($controller, "\$branchTotals[\$branchCode]['current'] +=") === false
        && strpos($controller, "\$branchTotals[\$branchCode]['compare'] +=") === false,
    'service_first_summary_key' => strpos($controller, "'service_first_analysis' => \$serviceFirstAnalysis") !== false,
    'mixed_totals_explicitly_disabled' => strpos($controller, "'mixed_service_totals_used' => false") !== false,
    'cross_service_score_disabled' => strpos($controller, "'cross_service_score_used' => false") !== false,
    'branch_named_service_lists' => strpos($view, 'Services that increased') !== false
        && strpos($view, 'Services that decreased') !== false,
    'named_priority_queue' => strpos($view, 'Largest service declines requiring review') !== false,
    'named_positive_signals' => strpos($view, 'Strongest service increases') !== false,
    'six_service_cards_source' => strpos($view, 'branch113-service-grid') !== false
        && strpos($view, 'foreach ($serviceRows as $service)') !== false,
    'latest_month_named_services' => strpos($view, 'Services that changed') !== false
        && strpos($view, "\$latestBranch['improved']") !== false
        && strpos($view, "\$latestBranch['declined']") !== false,
    'service_selector' => strpos($view, 'data-branch113-service-tab') !== false,
    'single_service_chart' => substr_count($view, 'id="branch113_service_chart"') === 1,
    'selected_service_monthly_table' => strpos($view, 'data-branch113-service-panel') !== false,
    'no_broad_improvement_copy' => strpos($view, 'Broad improvement') === false,
    'no_broad_decline_copy' => strpos($view, 'Broad decline') === false,
    'no_monthly_pulse' => strpos($view, 'MONTHLY EXECUTIVE PULSE') === false
        && strpos($view, 'branch127-pulse') === false,
    'no_branch_scorecards' => strpos($view, 'BRANCH SCORECARDS') === false,
    'no_higher_activity_kpi' => strpos($view, 'Higher activity') === false,
    'no_overall_branch_total_display' => strpos($view, 'current activity') === false
        && strpos($view, 'share_percent') === false,
    'nontechnical_error_copy' => stripos($view, 'Oracle') === false
        && stripos($view, 'query') === false,
    'service_chart_js' => strpos($js, 'activateService') !== false
        && strpos($js, 'renderService') !== false,
    'browser_gate' => strpos($js, 'DDB_BRANCH_COMPARISON_R45_P11_3_BROWSER_GATE') !== false,
    'responsive_service_cards' => strpos($css, '.branch113-service-grid') !== false
        && strpos($css, '@media(max-width:850px)') !== false,
    'asset_cache_busted' => strpos($layout, '11.0.11.98-r45-p11-3-service-first') !== false,
    'layout_service_first_description' => strpos($layout, 'See which named services increased or decreased in each branch.') !== false,
    'order_hotfix_preserved' => strpos($repo, 'ORDER BY 1, 2') !== false,
    'emergency_hotfix_preserved' => strpos($repo, 'clinic_id IN (16, 297, 298)') !== false
        && strpos($repo, 'r.clinic_id') === false,
    'six_union_contract_preserved' => substr_count($repo, 'UNION ALL') === 5,
    'revenue_summary_enabled' => preg_match('/^USE_REVENUE_SUMMARY=1$/m', $env) === 1,
    'revenue_summary_age_30' => preg_match('/^REVENUE_SUMMARY_MAX_AGE_HOURS=30$/m', $env) === 1,
    'oracle_contract_unchanged' => ($version['r45_p11_3']['oracle_contract_changed'] ?? true) === false,
    'query_count_unchanged' => ($version['r45_p11_3']['query_count_changed'] ?? true) === false,
    'oracle_writes_none' => ($version['r45_p11_3']['oracle_writes'] ?? '') === 'NONE',
];

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

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

exit($failed === [] ? 0 : 1);
