<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/app/bootstrap.php';

use App\Services\RevenuePerformanceProfiler;

$root = dirname(__DIR__);
$checks = [];
$add = static function (string $name, bool $ok, string $detail = '') use (&$checks): void {
    $checks[] = ['name' => $name, 'status' => $ok ? 'PASS' : 'FAIL', 'detail' => $detail];
};

$service = (string)file_get_contents($root . '/app/Services/RevenuePerformanceProfiler.php');
$tool = (string)file_get_contents($root . '/tools/revenue-performance-profile.php');
$controller = (string)file_get_contents($root . '/app/Controllers/RevenueController.php');
$repo = (string)file_get_contents($root . '/app/Repositories/RevenueRepository.php');
$version = json_decode((string)file_get_contents($root . '/DDB_VERSION.json'), true);

$add('version_release_11_0_11_55', ($version['release'] ?? '') === '11.0.11.55');
$add('phase_r45_p0', ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P0');
$add('profiler_service_exists', is_file($root . '/app/Services/RevenuePerformanceProfiler.php'));
$add('cli_profiler_exists', is_file($root . '/tools/revenue-performance-profile.php'));
$add('profile_outputs_five_artifacts', strpos($tool, 'REVENUE_PERFORMANCE_BASELINE.json') !== false && strpos($tool, 'REVENUE_QUERY_TIMINGS.csv') !== false && strpos($tool, 'REVENUE_ORACLE_OBJECT_DIAGNOSTICS.json') !== false && strpos($tool, 'REVENUE_YEAR_COMPARISON_CONTRACT.json') !== false && strpos($tool, 'REVENUE_MV_READINESS.json') !== false);
$add('five_query_call_baseline_documented', strpos($service, "'total_primary_query_calls_in_current_controller' => 5") !== false);
$add('four_revenue_scans_documented', strpos($service, "'revenue_source_scans_in_current_controller' => 4") !== false);
$add('controller_really_calls_monthly_revenue_four_times', substr_count($controller, '$repo->monthlyRevenue(') === 4, (string)substr_count($controller, '$repo->monthlyRevenue('));
$add('controller_really_calls_profit_loss_once', substr_count($controller, '$repo->monthlyProfitLoss(') === 1, (string)substr_count($controller, '$repo->monthlyProfitLoss('));
$add('source_table_contract_present', strpos($repo, 'T_INP_OUTP_REVENUE_BATCH') !== false);
$add('mv_contract_present', strpos($repo, 'MV_REVENUE_MONTHLY') !== false && strpos($service, 'user_mviews') !== false);
$add('index_diagnostics_present', strpos($service, 'user_indexes') !== false && strpos($service, 'user_ind_columns') !== false);
$add('table_statistics_diagnostics_present', strpos($service, 'user_tables') !== false && strpos($service, 'num_rows') !== false && strpos($service, 'last_analyzed') !== false);
$add('current_year_excludes_current_month_contract', strpos($service, 'CURRENT_YEAR_FAIR_COMPARISON') !== false && strpos($service, '$currentMonth - 1') !== false);
$add('past_years_full_12_month_contract', strpos($service, 'FULL_COMPLETED_YEAR_COMPARISON') !== false && strpos($service, 'range(1, 12)') !== false);
$add('read_only_contract', stripos($service . $tool, 'INSERT INTO') === false && stripos($service . $tool, 'UPDATE ') === false && stripos($service . $tool, 'DELETE FROM') === false && stripos($service . $tool, 'MERGE INTO') === false);
$add('no_controller_behavior_change_in_p0', strpos($controller, 'RevenuePerformanceProfiler') === false, 'P0 is diagnostic only');
$add('no_repository_behavior_change_marker', strpos($repo, 'H11.0-P11.1-R45-P0') === false, 'repository unchanged in P0');

$contractCurrent = RevenuePerformanceProfiler::yearComparisonContract(2026, 2025, new DateTimeImmutable('2026-07-15 12:00:00'));
$add('current_year_contract_jan_to_jun', ($contractCurrent['last_complete_month'] ?? null) === 6 && ($contractCurrent['comparison_months'] ?? []) === [1,2,3,4,5,6]);
$contractPast = RevenuePerformanceProfiler::yearComparisonContract(2025, 2024, new DateTimeImmutable('2026-07-15 12:00:00'));
$add('past_year_contract_full_year', ($contractPast['last_complete_month'] ?? null) === 12 && count((array)($contractPast['comparison_months'] ?? [])) === 12);

$fails = array_values(array_filter($checks, static function (array $c): bool { return $c['status'] !== 'PASS'; }));
$result = [
    'phase' => 'H11.0-P11.1-R45-P0',
    'title' => 'Revenue Performance Baseline, Year Comparison Contract & Query Profiling',
    'generated_at' => date(DATE_ATOM),
    'checks' => $checks,
    'pass' => count($checks) - count($fails),
    'fail' => count($fails),
    'status' => $fails === [] ? 'PASS' : 'FAIL',
    'write_operations' => 'NONE',
];

echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL;
exit($fails === [] ? 0 : 1);
