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

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.74',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P6.1',
    'policy_import' => strpos($controller, 'FairYearComparisonPolicy') !== false,
    'monthid_filter' => strpos($repo, 'MONTHID BETWEEN :start_month AND :end_month') !== false,
    'summary_month_contract' => strpos($repo, 'summary(int $year, int $compareYear, int $startMonth = 1, int $endMonth = 12)') !== false,
    'ranking_month_contract' => strpos($repo, 'specialtyRanking(int $year, string $metric, int $limit = 10, int $startMonth = 1, int $endMonth = 12)') !== false,
    'matrix_month_contract' => strpos($repo, 'specialtyMatrix(int $year, int $limit = 12, int $startMonth = 1, int $endMonth = 12)') !== false,
    'controller_applies_range' => 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, '.sf61-fair-comparison') !== false,
    'live_acceptance' => strpos($accept, 'DDB_SPECIALTY_FINANCE_R45_P6_1_LIVE_ACCEPTANCE_V1') !== false,
    'oracle_writes_none' => ($version['r45_p6_1']['oracle_writes'] ?? '') === 'NONE',
];

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