<?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');
$controller = (string)file_get_contents($root . '/app/Controllers/BranchComparisonController.php');
$view = (string)file_get_contents($root . '/app/Views/branch_comparison/index.php');
$layout = (string)file_get_contents($root . '/app/Views/layouts/main.php');
$css = (string)file_get_contents($root . '/public/assets/css/branch-comparison.css');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.90',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P11.2.1',
    'alias_order_removed' => strpos($repo, 'ORDER BY metric_key, month_id') === false,
    'positional_order_present' => strpos($repo, 'ORDER BY 1, 2') !== false,
    'root_cause_comment' => strpos($repo, 'Oracle compound-query compatibility') !== false,
    'six_union_contract_preserved' => substr_count($repo, 'UNION ALL') === 5,
    'six_metric_contract_preserved' => strpos($repo, "'outpatient'") !== false
        && strpos($repo, "'admissions'") !== false
        && strpos($repo, "'emergency'") !== false
        && strpos($repo, "'operations'") !== false
        && strpos($repo, "'laboratory'") !== false
        && strpos($repo, "'radiology'") !== false,
    'technical_error_logged' => strpos($controller, 'Branch Comparison source failure branch=') !== false,
    'public_error_is_generic' => strpos($controller, 'Review the live acceptance result for technical details.') !== false,
    'oracle_code_extracted' => strpos($controller, "preg_match('/ORA-\\\\d{5}/i'") !== false
        || strpos($controller, "preg_match('/ORA-\\d{5}/i'") !== false,
    'raw_error_not_assigned_to_view' => strpos($controller, "'message' => \$this->safeError") === false,
    'ui_shows_code_only' => strpos($view, "<code><?= e((string)\$error['code']) ?></code>") !== false,
    'safe_code_style' => strpos($css, '.branch112-error-grid code') !== false,
    'cache_busted' => strpos($layout, '11.0.11.90-r45-p11-2-1-oracle-order-hotfix') !== false,
    'data_contract_unchanged' => ($version['r45_p11_2_1']['data_contract_changed'] ?? true) === false,
    'query_count_unchanged' => ($version['r45_p11_2_1']['query_count_changed'] ?? true) === false,
    'oracle_writes_none' => ($version['r45_p11_2_1']['oracle_writes'] ?? '') === 'NONE',
];

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

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