<?php
declare(strict_types=1);

$root = dirname(__DIR__);
$version = json_decode((string)file_get_contents($root . '/DDB_VERSION.json'), true);
$config = (string)file_get_contents($root . '/config/app.php');

function activeEnvValues(string $path, array $keys): array
{
    $values = [];
    $counts = array_fill_keys($keys, 0);
    foreach (file($path, FILE_IGNORE_NEW_LINES) ?: [] as $line) {
        if (preg_match('/^\s*([A-Z0-9_]+)\s*=(.*)$/', (string)$line, $matches) !== 1) {
            continue;
        }
        $key = (string)$matches[1];
        if (!in_array($key, $keys, true)) {
            continue;
        }
        $counts[$key]++;
        $values[$key] = trim((string)$matches[2]);
    }
    return ['values' => $values, 'counts' => $counts];
}

$keys = ['USE_REVENUE_SUMMARY', 'REVENUE_SUMMARY_MAX_AGE_HOURS'];
$env = activeEnvValues($root . '/.env', $keys);
$example = activeEnvValues($root . '/.env.example', $keys);
$template = activeEnvValues($root . '/.env.oranjc_hp.template', $keys);

$checks = [
    'version' => ($version['version'] ?? '') === '11.0.11.91',
    'phase' => ($version['phase'] ?? '') === 'H11.0-P11.1-R45-P11.2.2',
    'env_summary_enabled' => ($env['values']['USE_REVENUE_SUMMARY'] ?? '') === '1',
    'env_max_age_30' => ($env['values']['REVENUE_SUMMARY_MAX_AGE_HOURS'] ?? '') === '30',
    'env_no_duplicate_summary_key' => ($env['counts']['USE_REVENUE_SUMMARY'] ?? 0) === 1,
    'env_no_duplicate_age_key' => ($env['counts']['REVENUE_SUMMARY_MAX_AGE_HOURS'] ?? 0) === 1,
    'example_summary_enabled' => ($example['values']['USE_REVENUE_SUMMARY'] ?? '') === '1',
    'example_max_age_30' => ($example['values']['REVENUE_SUMMARY_MAX_AGE_HOURS'] ?? '') === '30',
    'template_summary_enabled' => ($template['values']['USE_REVENUE_SUMMARY'] ?? '') === '1',
    'template_max_age_30' => ($template['values']['REVENUE_SUMMARY_MAX_AGE_HOURS'] ?? '') === '30',
    'config_reads_summary_flag' => strpos($config, "env('USE_REVENUE_SUMMARY', '0')") !== false,
    'config_reads_max_age' => strpos($config, "env('REVENUE_SUMMARY_MAX_AGE_HOURS', '30')") !== false,
    'credentials_preserved_contract' => ($version['r45_p11_2_2']['credentials_preserved'] ?? false) === true,
    'oracle_writes_none' => ($version['r45_p11_2_2']['oracle_writes'] ?? '') === 'NONE',
];

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

echo json_encode([
    'schema' => 'R45_P11_2_2_REVENUE_SUMMARY_ENV_QA',
    'checks' => $checks,
    'passed' => count($checks) - count($failed),
    'failed' => $failed,
    'effective_env' => $env['values'],
    'oracle_writes' => 'NONE',
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;

exit($failed === [] ? 0 : 1);
