<?php

declare(strict_types=1);

$root = dirname(__DIR__);
$checks = [];
function add_check(array &$checks, string $name, bool $ok, string $detail = ''): void {
    $checks[] = ['name' => $name, 'ok' => $ok, 'detail' => $detail];
}
function read_json_file(string $path): array {
    if (!is_file($path)) return [];
    $raw = file_get_contents($path);
    if ($raw === false) return [];
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}
function read_csv_rows(string $path): array {
    if (!is_file($path)) return [];
    $fh = fopen($path, 'rb');
    if ($fh === false) return [];
    $header = fgetcsv($fh);
    if (!is_array($header)) { fclose($fh); return []; }
    if (isset($header[0])) $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', (string)$header[0]);
    $rows = [];
    while (($data = fgetcsv($fh)) !== false) {
        if (count($data) !== count($header)) continue;
        $rows[] = array_combine($header, $data);
    }
    fclose($fh);
    return $rows;
}

$version = read_json_file($root . '/DDB_VERSION.json');
$snapshot = read_json_file($root . '/docs/baseline/PHASE_10_8_BASELINE_SNAPSHOT.json');
$protected = read_json_file($root . '/docs/baseline/PROTECTED_CORE_HASHES.json');
$legacy = read_csv_rows($root . '/docs/legacy/LEGACY_FUNCTION_MASTER_MATRIX.csv');
$routes = read_csv_rows($root . '/docs/legacy/LEGACY_ROUTE_MAP.csv');
$permissions = read_csv_rows($root . '/docs/legacy/LEGACY_PERMISSION_MAP.csv');
$filters = read_csv_rows($root . '/docs/legacy/LEGACY_FILTER_MAP.csv');

add_check($checks, 'release_version', ($version['release'] ?? '') === '10.8.0', (string)($version['release'] ?? 'missing'));
add_check($checks, 'baseline_snapshot', ($snapshot['baseline_version'] ?? '') === '10.7.2', (string)($snapshot['baseline_version'] ?? 'missing'));
add_check($checks, 'legacy_dispatcher_inventory_count', count($legacy) === 31, (string)count($legacy) . ' / 31');

$validStatuses = ['PARITY_PASS','PARTIAL','MISSING','BLOCKED_SOURCE_MISSING','APPROVED_REPLACEMENT'];
$statusCounts = [];
$invalid = [];
foreach ($legacy as $row) {
    $status = (string)($row['status'] ?? '');
    $statusCounts[$status] = ($statusCounts[$status] ?? 0) + 1;
    if (!in_array($status, $validStatuses, true)) $invalid[] = $status;
}
add_check($checks, 'legacy_status_values_valid', count($invalid) === 0, count($invalid) === 0 ? 'valid controlled vocabulary' : implode(', ', $invalid));
add_check($checks, 'no_false_parity_pass', (int)($statusCounts['PARITY_PASS'] ?? 0) === 0, 'PARITY_PASS=' . (int)($statusCounts['PARITY_PASS'] ?? 0));
add_check($checks, 'partial_legacy_functions_exposed', (int)($statusCounts['PARTIAL'] ?? 0) === 18, 'PARTIAL=' . (int)($statusCounts['PARTIAL'] ?? 0));
add_check($checks, 'missing_legacy_functions_exposed', (int)($statusCounts['MISSING'] ?? 0) === 13, 'MISSING=' . (int)($statusCounts['MISSING'] ?? 0));
add_check($checks, 'route_inventory_ready', count($routes) >= 18, (string)count($routes) . ' route records');
add_check($checks, 'permission_inventory_ready', count($permissions) >= 3, (string)count($permissions) . ' permission records');
add_check($checks, 'filter_inventory_ready', count($filters) >= 7, (string)count($filters) . ' filter records');

$filterNames = array_map(static function(array $r): string { return (string)($r['filter'] ?? ''); }, $filters);
add_check($checks, 'legacy_date_range_filters_recorded', in_array('from_date_v', $filterNames, true) && in_array('to_date_v', $filterNames, true), 'from_date_v + to_date_v');
add_check($checks, 'legacy_compare_year_recorded', in_array('to_year', $filterNames, true), 'to_year');

$protectedOk = true; $protectedChecked = 0; $protectedMismatch = [];
foreach (($protected['files'] ?? []) as $item) {
    $path = $root . '/' . (string)($item['path'] ?? '');
    $expected = strtolower((string)($item['sha256'] ?? ''));
    $protectedChecked++;
    if (!is_file($path) || strtolower((string)hash_file('sha256', $path)) !== $expected) {
        $protectedOk = false;
        $protectedMismatch[] = (string)($item['path'] ?? 'unknown');
    }
}
add_check($checks, 'protected_core_unchanged', $protectedOk && $protectedChecked >= 8, $protectedOk ? ($protectedChecked . ' hashes match') : implode(', ', $protectedMismatch));
add_check($checks, 'executive_leadership_standard_present', is_file($root . '/docs/executive_leadership_ui_standard_v1.md'), 'Executive Leadership UI Standard v1.0');
add_check($checks, 'legacy_source_boundary_documented', is_file($root . '/docs/legacy/LEGACY_SOURCE_COVERAGE.md'), 'No invented parity when legacy source is incomplete');
add_check($checks, 'next_phase_is_revenue_parity', ($snapshot['next_priority'] ?? '') === 'Phase 10.9 - Revenue Legacy Functional Parity', (string)($snapshot['next_priority'] ?? 'missing'));

$pass = 0; $fail = 0;
foreach ($checks as $check) { if ($check['ok']) $pass++; else $fail++; }

header('Content-Type: text/plain; charset=UTF-8');
echo "DDB Master Baseline & Legacy Inventory QA\n";
echo "Phase: 10.8 - Master Baseline, Complete Legacy Inventory & Patch Control Center Foundation\n";
echo "Write operations: NONE\n\n";
echo "QA Gates:\n";
foreach ($checks as $check) {
    echo '[' . ($check['ok'] ? 'PASS' : 'FAIL') . '] ' . str_pad($check['name'], 44) . ' | ' . $check['detail'] . "\n";
}
echo "\nInventory Summary:\n";
echo 'known_legacy_functions   | ' . count($legacy) . "\n";
echo 'parity_pass             | ' . (int)($statusCounts['PARITY_PASS'] ?? 0) . "\n";
echo 'partial                 | ' . (int)($statusCounts['PARTIAL'] ?? 0) . "\n";
echo 'missing                 | ' . (int)($statusCounts['MISSING'] ?? 0) . "\n";
echo 'current_routes_recorded | ' . count($routes) . "\n";
echo 'protected_core_hashes   | ' . $protectedChecked . "\n";
echo "\nQA result: " . ($fail === 0 ? 'PASS' : 'FAIL') . "\n";
echo "PASS gates: {$pass}\n";
echo "FAIL gates: {$fail}\n";
echo "No Oracle row, review row, governance row or audit row is modified.\n";
