<?php
declare(strict_types=1);

$root = dirname(__DIR__);
$version = json_decode((string)file_get_contents($root . '/DDB_VERSION.json'), true);
$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');
$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.97',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P11.2.8',
    'management_formatter' => strpos($view, '$monthlyManagementMessage') !== false,
    'broad_improvement' => strpos($view, "Broad improvement', 'تحسن واسع") !== false,
    'broad_decline' => strpos($view, "Broad decline', 'تراجع واسع") !== false,
    'balanced_movement' => strpos($view, "Balanced movement', 'حركة متوازنة") !== false,
    'complete_improvement_sentence' => strpos($view, "of 6 service areas improved") !== false,
    'complete_decline_sentence' => strpos($view, "of 6 service areas declined") !== false,
    'arrow_notation_removed' => strpos($view, '?>↑') === false
        && strpos($view, '?>↓') === false
        && strpos($view, "['improving']) ?>↑") === false
        && strpos($view, "['declining']) ?>↓") === false,
    'latest_summary_plain_language' => strpos($view, '$latestMessage') !== false,
    'difference_summary_plain_language' => strpos($view, '$differenceMessage') !== false,
    'review_card_plain_language' => strpos($view, "Broad decline:', 'تراجع واسع:") !== false,
    'pulse_sentence_css' => strpos($css, '.branch127-pulse-row article>small') !== false,
    'asset_cache_busted' => strpos($layout, '11.0.11.97-r45-p11-2-8-management-language') !== false,
    'order_hotfix_preserved' => strpos($repo, 'ORDER BY 1, 2') !== false,
    'emergency_hotfix_preserved' => strpos($repo, 'clinic_id IN (16, 297, 298)') !== false,
    '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_2_8']['oracle_contract_changed'] ?? true) === false,
    'query_count_unchanged' => ($version['r45_p11_2_8']['query_count_changed'] ?? true) === false,
    'oracle_writes_none' => ($version['r45_p11_2_8']['oracle_writes'] ?? '') === 'NONE',
];

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

echo json_encode([
    'schema' => 'R45_P11_2_8_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);
