<?php
declare(strict_types=1);

// Compare only sanitized hashes, JSON type graphs and source-presence branches.
// Never echo response bodies or a private journal's token.
function batch_result_empty_branch(array $result): bool
{
    $shape = $result['response_shape'] ?? null;
    if (is_array($shape) && isset($shape['list']) && is_array($shape['list'])) {
        if ($shape['list'] === [] || (isset($shape['list']['data'])
            && $shape['list']['data'] === [])) return true;
    }
    return ($result['branch'] ?? '') === 'empty_only';
}

function compare_batch_results(array $a, array $b, array $c): array
{
    $summary = ['ab_exact' => 0, 'ab_same_error' => 0, 'ab_mismatch' => 0,
        'c_type_match' => 0, 'c_type_mismatch' => 0,
        'c_snapshot_branch_unmatched' => 0, 'c_business_red' => 0,
        'missing_lane' => 0, 'not_requested' => 0, 'routes' => []];
    $keys = array_unique(array_merge(array_keys($a), array_keys($b), array_keys($c)));
    sort($keys, SORT_STRING);
    foreach ($keys as $key) {
        $ar = $a[$key] ?? null;
        $br = $b[$key] ?? null;
        $cr = $c[$key] ?? null;
        if (!is_array($ar) || !is_array($br) || !is_array($cr)) {
            $summary['missing_lane']++;
            $summary['routes'][$key] = 'missing_lane';
            continue;
        }
        if (($ar['state'] ?? '') === 'source_blocked'
            && ($br['state'] ?? '') === 'source_blocked'
            && ($cr['state'] ?? '') === 'source_blocked') {
            $summary['not_requested']++;
            $summary['routes'][$key] = 'not_requested_source_blocked';
            continue;
        }
        $abEqual = ($ar['business_status'] ?? null) === ($br['business_status'] ?? null)
            && ($ar['data_sha256'] ?? null) === ($br['data_sha256'] ?? null)
            && ($ar['response_shape'] ?? null) === ($br['response_shape'] ?? null);
        if (!$abEqual) {
            $summary['ab_mismatch']++;
            $summary['routes'][$key] = 'ab_mismatch';
            continue;
        }
        if ((int)($ar['business_status'] ?? 0) !== 200) {
            $summary['ab_same_error']++;
            $summary['routes'][$key] = 'ab_same_error';
            continue;
        }
        $summary['ab_exact']++;
        if ((int)($cr['business_status'] ?? 0) !== 200) {
            $summary['c_business_red']++;
            $summary['routes'][$key] = 'c_business_red';
            continue;
        }
        $aSource = (int)($ar['source']['rows_sampled'] ?? 0) > 0;
        $cSource = (int)($cr['source']['rows_sampled'] ?? 0) > 0;
        if ($aSource !== $cSource) {
            $summary['c_snapshot_branch_unmatched']++;
            $summary['routes'][$key] = 'c_snapshot_branch_unmatched';
            continue;
        }
        if (batch_result_empty_branch($ar) !== batch_result_empty_branch($cr)) {
            $summary['c_snapshot_branch_unmatched']++;
            $summary['routes'][$key] = 'c_snapshot_branch_unmatched';
            continue;
        }
        if (($ar['response_shape'] ?? null) === ($cr['response_shape'] ?? null)) {
            $summary['c_type_match']++;
            $summary['routes'][$key] = 'c_type_match';
        } else {
            $summary['c_type_mismatch']++;
            $summary['routes'][$key] = 'c_type_mismatch';
        }
    }
    return $summary;
}

if (isset($_SERVER['SCRIPT_FILENAME']) && realpath($_SERVER['SCRIPT_FILENAME']) === __FILE__) {
    if (($argv[1] ?? '') !== '--compare' || count($argv) !== 8) {
        echo json_encode(['status' => 'default_deny']), PHP_EOL;
        exit(78);
    }
    $sets = [[], [], []];
    for ($i = 0; $i < 6; $i++) {
        $path = $argv[$i + 2];
        if (!is_file($path) || is_link($path) || filesize($path) > 1048576) {
            echo json_encode(['status' => 'input_blocked']), PHP_EOL;
            exit(2);
        }
        $raw = json_decode((string)file_get_contents($path), true);
        $rows = is_array($raw) ? ($raw['results'] ?? $raw['routes'] ?? null) : null;
        if (!is_array($rows)) {
            echo json_encode(['status' => 'input_shape_blocked']), PHP_EOL;
            exit(2);
        }
        $sets[intdiv($i, 2)] = array_merge($sets[intdiv($i, 2)], $rows);
    }
    echo json_encode(compare_batch_results($sets[0], $sets[1], $sets[2]),
        JSON_UNESCAPED_SLASHES), PHP_EOL;
}
