<?php
$root = dirname(__DIR__);
$version = json_decode(file_get_contents($root . '/DDB_VERSION.json'), true);
$profiler = file_get_contents($root . '/tools/visits-performance-profiler.php');
$audit = file_get_contents($root . '/tools/visits-sql-static-audit.php');
$repo = file_get_contents($root . '/app/Repositories/VisitsRepository.php');

$datasets = [
    'monthly_outpatient_visits',
    'monthly_emergency_visits',
    'monthly_admissions',
    'followup_mix',
    'admission_category_mix',
    'outpatient_cash_credit_today',
    'daily_outpatient_trend_14d',
    'top_specialties_by_op_visits',
];

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.68',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P5.0',
    'profiler_schema' => strpos($profiler, 'DDB_VISITS_PERFORMANCE_PROFILE_V1') !== false,
    'static_audit_schema' => strpos($audit, 'DDB_VISITS_SQL_STATIC_AUDIT_V1') !== false,
    'new_repository_per_iteration' => strpos($profiler, 'new VisitsRepository($hospital)') !== false,
    'json_evidence' => strpos($profiler, 'VISITS_PERFORMANCE_PROFILE_') !== false,
    'csv_evidence' => strpos($profiler, "fputcsv") !== false,
    'same_year_guard' => strpos($profiler, 'Current and comparison years must be different') !== false,
    'source_repository_unchanged' => strpos($repo, 'DDB_VISITS_PERFORMANCE_PROFILE_V1') === false,
    'php7_compatible' => strpos($profiler, 'str_contains(') === false,
];

foreach ($datasets as $dataset) {
    $checks['dataset_' . $dataset] = strpos($profiler, "'" . $dataset . "'") !== false;
}

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