<?php
$root = dirname(__DIR__);
$version = json_decode(file_get_contents($root . '/DDB_VERSION.json'), true);
$repo = file_get_contents($root . '/app/Repositories/VisitsRepository.php');
$controller = file_get_contents($root . '/app/Controllers/OperationsController.php');
$profiler = file_get_contents($root . '/tools/visits-performance-profiler.php');
$acceptance = file_get_contents($root . '/tools/visits-r45-p5-1-live-acceptance.php');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.69',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P5.1',
    'bundle_method' => strpos($repo, 'public function monthlyVisitBundle(') !== false,
    'single_page_bundle_call' => substr_count($controller, 'monthlyVisitBundle(') === 1,
    'page_no_separate_opd_call' => strpos($controller, 'return $repo->monthlyOutpatientVisits(') === false,
    'page_no_separate_er_call' => strpos($controller, 'return $repo->monthlyEmergencyVisits(') === false,
    'bundle_opd_case' => strpos($repo, 'opd_current_value') !== false,
    'bundle_er_case' => strpos($repo, 'er_current_value') !== false,
    'year_date_range' => strpos($repo, "sprintf('%04d-01-01', \$year)") !== false,
    'followup_extract_removed' => strpos($repo, 'EXTRACT(YEAR FROM r.expecteddonedate) = :year') === false,
    'admission_category_extract_removed' => strpos($repo, 'EXTRACT(YEAR FROM v.visit_start_date) = :acty_year') === false,
    'monthly_visit_extract_filter_removed' => strpos($repo, 'EXTRACT(YEAR FROM r.expecteddonedate) IN') === false,
    'admission_extract_filter_removed' => strpos($repo, 'EXTRACT(YEAR FROM v.visit_start_date) IN') === false,
    'daily_trunc_filter_removed' => strpos($repo, 'TRUNC(r.expecteddonedate) >=') === false
        && strpos($repo, 'TRUNC(r.expecteddonedate) <=') === false,
    'daily_upper_bound' => strpos($repo, 'r.expecteddonedate < TRUNC(SYSDATE) + 1') !== false,
    'legacy_public_contracts_preserved' => strpos($repo, 'public function monthlyOutpatientVisits(') !== false
        && strpos($repo, 'public function monthlyEmergencyVisits(') !== false,
    'profiler_uses_bundle' => strpos($profiler, 'monthly_opd_er_consolidated_bundle') !== false,
    'live_parity_tool' => strpos($acceptance, 'numeric_parity') !== false,
    'no_oracle_ddl' => stripos($repo . $controller, 'CREATE TABLE') === false
        && stripos($repo . $controller, 'CREATE INDEX') === false,
    'oracle_writes_none' => ($version['r45_p5_1']['oracle_writes'] ?? '') === 'NONE',
];

$failed = [];
foreach ($checks as $name => $ok) {
    if (!$ok) $failed[] = $name;
}
echo json_encode([
    'schema' => 'R45_P5_1_QA',
    'checks' => $checks,
    'passed' => count($checks) - count($failed),
    'failed' => $failed,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;
exit(count($failed) === 0 ? 0 : 1);
