<?php
$root = dirname(__DIR__);
$version = json_decode(file_get_contents($root . '/DDB_VERSION.json'), true);
$repo = file_get_contents($root . '/app/Repositories/BedsRepository.php');
$controller = file_get_contents($root . '/app/Controllers/BedsController.php');
$view = file_get_contents($root . '/app/Views/beds/index.php');
$css = file_get_contents($root . '/public/assets/css/beds-executive-parity.css');
$layout = file_get_contents($root . '/app/Views/layouts/main.php');
$accept = file_get_contents($root . '/tools/beds-r45-p8-1-live-acceptance.php');

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.78',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P8.1',
    'policy_import' => strpos($controller, 'FairYearComparisonPolicy') !== false,
    'compare_year_request' => strpos($controller, "Request::get('compare_year')") !== false,
    'matched_periods' => strpos($controller, 'comparisonPeriods(') !== false,
    'safe_shift' => strpos($repo, 'public static function shiftDateToYear(') !== false,
    'current_and_compare_units' => strpos($controller, "'compare_units' =>") !== false,
    'current_and_compare_beds' => strpos($controller, "'compare_beds' =>") !== false,
    'comparison_control' => strpos($view, 'Comparison year') !== false,
    'fair_notice' => strpos($view, 'Fair current-year comparison') !== false,
    'arabic_notice' => strpos($view, 'مقارنة عادلة للسنة الحالية') !== false,
    'live_snapshot_separated' => strpos($view, 'Live capacity is shown separately') !== false,
    'unit_comparison_table' => strpos($view, '$unitComparison as $idx => $row') !== false,
    'bed_comparison_table' => strpos($view, '$bedComparison as $row') !== false,
    'comparison_css' => strpos($css, '.beds81-comparison-notice') !== false,
    'cache_identity' => strpos(
        $layout,
        'beds-executive-parity.css?v=11.0.11.78-r45-p8-1-fair-year-comparison'
    ) !== false,
    'live_acceptance' => strpos($accept, 'DDB_BEDS_R45_P8_1_LIVE_ACCEPTANCE_V1') !== false,
    'oracle_writes_none' => ($version['r45_p8_1']['oracle_writes'] ?? '') === 'NONE',
];

$failed = [];
foreach ($checks as $name => $ok) {
    if (!$ok) $failed[] = $name;
}

echo json_encode([
    'schema' => 'R45_P8_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);
