<?php
$root = dirname(__DIR__);
$repo = file_get_contents($root . '/app/Repositories/RevenueRepository.php');
$plan = file_get_contents($root . '/tools/revenue-sql-plan-profile.php');
$version = json_decode(file_get_contents($root . '/DDB_VERSION.json'), true);

$checks = [
    'version' => isset($version['version']) && $version['version'] === '11.0.11.61',
    'phase' => isset($version['phase']) && $version['phase'] === 'H11.0-P11.1-R45-P2.2.1.2',
    'select_visit_month' => strpos($repo, 'VISIT_MONTH AS MONTHID') !== false,
    'group_by_visit_month' => strpos($repo, 'GROUP BY YEARID, VISIT_MONTH') !== false,
    'mismatch_removed' => strpos($repo, "TO_NUMBER(TO_CHAR(VISIT_END_DATE, 'MM')) AS MONTHID") === false,
    'display_cursor_present' => strpos($plan, 'DISPLAY_CURSOR') !== false,
    'invalid_cardinality_token_removed' => strpos($plan, '+CARDINALITY') === false,
    'valid_plan_format' => strpos($plan, 'ALLSTATS LAST +PREDICATE +COST +BYTES') !== false,
    'no_explain_plan' => strpos($plan, 'EXPLAIN PLAN FOR') === false,
];

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