<?php
$root = dirname(__DIR__);
$version = json_decode(file_get_contents($root . '/DDB_VERSION.json'), true);
$repo = file_get_contents($root . '/app/Repositories/DoctorsRepository.php');
$controller = file_get_contents($root . '/app/Controllers/DoctorsController.php');
$view = file_get_contents($root . '/app/Views/doctors/index.php');
$css = file_get_contents($root . '/public/assets/css/executive-ui-core.css');
$accept = file_get_contents($root . '/tools/doctors-r45-p7-1-live-acceptance.php');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.75',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P7.1',
    'policy_import' => strpos($controller, 'FairYearComparisonPolicy') !== false,
    'month_filter' => strpos($repo, 'MONTHID BETWEEN :start_month AND :end_month') !== false,
    'summary_contract' => strpos($repo, 'summary(int $year, int $compareYear, int $startMonth = 1, int $endMonth = 12)') !== false,
    'top_doctors_contract' => strpos($repo, 'topDoctors(int $year, string $metric = \'TOT_REV\', int $limit = 10, int $startMonth = 1, int $endMonth = 12)') !== false,
    'specialties_contract' => strpos($repo, 'specialties(int $year, string $metric = \'TOT_REV\', int $limit = 10, int $startMonth = 1, int $endMonth = 12)') !== false,
    'mix_contract' => strpos($repo, 'revenueMix(int $year, int $startMonth = 1, int $endMonth = 12)') !== false,
    'controller_applies_contract' => strpos($controller, '$startMonth = (int)($comparisonContract') !== false,
    'period_labels' => strpos($controller, 'periodLabel(') !== false,
    'view_notice' => strpos($view, 'Fair current-year comparison') !== false,
    'arabic_notice' => strpos($view, 'مقارنة عادلة للسنة الحالية') !== false,
    'css_notice' => strpos($css, '.doctors71-fair-comparison') !== false,
    'live_acceptance' => strpos($accept, 'DDB_DOCTORS_R45_P7_1_LIVE_ACCEPTANCE_V1') !== false,
    'oracle_writes_none' => ($version['r45_p7_1']['oracle_writes'] ?? '') === 'NONE',
];

$failed = [];
foreach ($checks as $name => $ok) {
    if (!$ok) $failed[] = $name;
}
echo json_encode([
    'schema' => 'R45_P7_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);
