<?php
$root = dirname(__DIR__);
$version = json_decode(file_get_contents($root . '/DDB_VERSION.json'), true);
$discovery = file_get_contents($root . '/tools/specialty-finance-monthly-grain-discovery.php');
$audit = file_get_contents($root . '/tools/specialty-finance-fair-comparison-static-audit.php');
$repo = file_get_contents($root . '/app/Repositories/SpecialtyFinanceRepository.php');
$controller = file_get_contents($root . '/app/Controllers/SpecialtyFinanceController.php');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.71',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P6.0',
    'discovery_schema' => strpos($discovery, 'DDB_SPECIALTY_FINANCE_MONTHLY_GRAIN_DISCOVERY_V1') !== false,
    'all_tab_columns_inventory' => strpos($discovery, 'all_tab_columns') !== false,
    'year_coverage' => strpos($discovery, 'year_coverage') !== false,
    'date_candidate_profile' => strpos($discovery, "TO_CHAR({\$column}, 'YYYY-MM')") !== false,
    'month_id_candidate_profile' => strpos($discovery, 'numeric month-grain column') !== false,
    'identifier_guard' => strpos($discovery, 'Unsafe Oracle identifier') !== false,
    'json_evidence' => strpos($discovery, 'SPECIALTY_FINANCE_MONTHLY_GRAIN_DISCOVERY_') !== false,
    'csv_evidence' => strpos($discovery, 'SPECIALTY_FINANCE_COLUMN_CANDIDATES_') !== false,
    'static_audit_schema' => strpos($audit, 'DDB_SPECIALTY_FINANCE_FAIR_COMPARISON_STATIC_AUDIT_V1') !== false,
    'repository_unchanged' => strpos($repo, 'DDB_SPECIALTY_FINANCE_MONTHLY_GRAIN_DISCOVERY_V1') === false,
    'controller_unchanged' => strpos($controller, 'DDB_SPECIALTY_FINANCE_MONTHLY_GRAIN_DISCOVERY_V1') === false,
    'oracle_writes_none' => ($version['r45_p6_0']['oracle_writes'] ?? '') === 'NONE',
];

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