<?php
$root = dirname(__DIR__);
$version = json_decode(file_get_contents($root . '/DDB_VERSION.json'), true);
$controller = file_get_contents($root . '/app/Controllers/OperationsController.php');
$view = file_get_contents($root . '/app/Views/operations/module.php');
$css = file_get_contents($root . '/public/assets/css/executive-ui-core.css');
$policy = file_get_contents($root . '/app/Services/FairYearComparisonPolicy.php');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.70',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P5.1.1',
    'shared_policy_imported' => strpos($controller, 'use App\\Services\\FairYearComparisonPolicy;') !== false,
    'shared_policy_resolved' => strpos($controller, 'new FairYearComparisonPolicy()') !== false,
    'policy_contract_unchanged' => strpos($policy, 'only completed months') !== false,
    'contract_passed_to_builder' => strpos($controller, '$visitsComparisonContract') !== false,
    'fair_range_applied' => strpos($controller, "\$comparisonContract['from_date']") !== false
        && strpos($controller, "\$comparisonContract['to_date']") !== false,
    'no_completed_month_guard' => strpos($controller, '$hasComparableCompletedMonths') !== false,
    'monthly_rows_filtered' => strpos($controller, 'filterMonthlyRows(') !== false,
    'period_labels_same_months' => strpos($controller, 'monthRangeLabel(') !== false,
    'view_notice' => strpos($view, 'Fair current-year comparison') !== false,
    'arabic_notice' => strpos($view, 'مقارنة عادلة للسنة الحالية') !== false,
    'current_month_excluded_text' => strpos($view, 'current month') !== false
        && strpos($view, 'الشهر الحالي') !== false,
    'notice_css' => strpos($css, '.visits31-fair-comparison') !== false,
    'daily_live_metrics_preserved' => strpos($controller, 'dailyOutpatientTrend(14)') !== false,
    'oracle_writes_none' => ($version['r45_p5_1_1']['oracle_writes'] ?? '') === 'NONE',
];

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