#!/usr/bin/env python3
"""Independent blind recomputation (D-050) for Phase 2 (#57 AI Judge Flagship Audit).

Written strictly from PLAN.md, DRYRUN.md, and raw pinned input schemas prior to
reading any primary analysis scripts or output summaries.
"""

from __future__ import annotations

import argparse
import csv
import gzip
import hashlib
import itertools
import json
import math
import re
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any

import numpy as np
import pyarrow.parquet as pq


EXPECTED_SHA256 = {
    "rb1_filtered_parquet": "65473c20ed0627e02503557ae102c25c6b0e66b5ed69ee327e224bb95e70ca29",
    "rb2_test_parquet": "c8ec60efbd75d2f9dcba4121e6101f7a6015abc38a34e034ae2c7ae886265958",
    "items_csv_gz": "375cc747e24e7cf6f30541ae142e79b3b0087cbbaf4e67e1c19776f832d488bb",
    "labels_frozen_json": "3cdb11e3b2f035ef3cbbced98a0a14926ac2f34976f436388b09b48dd60d786d",
    "input_manifest_json": "0827486090e8fccac50282091a053430368e7d8c561faecc9b200cc73f43f899",
}

MODEL_SCORE_FILES = {
    "M1": "scores_M1_qwen25_1p5b.json",
    "M2": "scores_M2_smollm2_1p7b.json",
    "M3": "scores_M3_qwen3_4b.json",
    "M4": "scores_M4_mistral_7b_q4km.json",
}

C2_SLICES = [
    "rb1_math_prm_disjoint",
    "rb2_math_llm_vs_llm",
    "rb1_hep_python_sym",
    "rb1_llmbar_adver_asym",
]

C3_ARMS = ["O", "S", "A", "RS", "RA"]
C3_CONTRASTS = [
    ("RA", "RS"),
    ("A", "S"),
    ("RS", "S"),
    ("RA", "A"),
    ("S", "O"),
]


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def scaffolding_score(text: str) -> float:
    """Text-only surface scaffolding density per log2(words + 16)."""
    words = len(re.findall(r"\S+", text))
    headings = len(re.findall(r"(?m)^\s*#{1,6}\s+", text))
    bullets = len(re.findall(r"(?m)^\s*[-•]\s+", text))
    numbered = len(re.findall(r"(?m)^\s*\d+\.\s+", text))
    step_headers = len(re.findall(r"(?im)^\s*(?:\*\*)?step\s+\d+\b", text))
    has_boxed = 1 if "\\boxed" in text else 0
    discourse = len(
        re.findall(
            r"(?i)\b(?:therefore|thus|hence|let's|we\s+can|to\s+find)\b",
            text,
        )
    )
    numerator = 1.5 * (headings + bullets + numbered + step_headers + has_boxed) + 1.0 * discourse
    return float(numerator / math.log2(words + 16))


def conditional_yes_bounds_from_mass(p_yes: float, p_no: float, omitted: float) -> tuple[float, float]:
    om = max(0.0, float(omitted))
    denom = float(p_yes) + float(p_no) + om
    if denom <= 0.0:
        return (0.0, 1.0)
    return (float(p_yes) / denom, (float(p_yes) + om) / denom)


def pair_win_interval(interval_c: tuple[float, float], interval_r: tuple[float, float]) -> tuple[float, float]:
    lo_c, hi_c = interval_c
    lo_r, hi_r = interval_r
    win_lo = 1.0 if lo_c > hi_r else (0.5 if lo_c == hi_r else 0.0)
    win_hi = 1.0 if hi_c > lo_r else (0.5 if hi_c == lo_r else 0.0)
    return (win_lo, win_hi)


def midpoint_win(mid_c: float, mid_r: float) -> float:
    if mid_c > mid_r:
        return 1.0
    if mid_c == mid_r:
        return 0.5
    return 0.0


def mann_whitney_auroc(pos_scores: list[float], neg_scores: list[float]) -> float:
    pos = np.asarray(pos_scores, dtype=np.float64)
    neg = np.asarray(neg_scores, dtype=np.float64)
    gt = (pos[:, None] > neg[None, :]).sum()
    eq = (pos[:, None] == neg[None, :]).sum()
    return float((gt + 0.5 * eq) / (len(pos) * len(neg)))


def bootstrap_mean_ci(values: np.ndarray, n_boot: int, seed: int) -> tuple[float, float]:
    rng = np.random.default_rng(seed)
    n = len(values)
    idx = rng.integers(0, n, size=(n_boot, n))
    means = values[idx].mean(axis=1)
    lo, hi = np.percentile(means, [2.5, 97.5])
    return (float(lo), float(hi))


# ---------------------------------------------------------------------------
# C1 (H1): Lincoln-Petersen Covariance Identity & Zero-Shot Lift Calibration
# ---------------------------------------------------------------------------
def recompute_c1(items_csv_gz: Path) -> dict[str, Any]:
    pools: dict[str, dict[str, list[tuple[str, int, int, float]]]] = defaultdict(lambda: defaultdict(list))
    with gzip.open(items_csv_gz, "rt", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            if row["judge_id"] == "V0":
                continue
            pools[row["pool"]][row["judge_id"]].append(
                (
                    str(row["prompt_id"]),
                    int(row["completion_idx"]),
                    int(row["gold_correct"]),
                    float(row["score"]),
                )
            )

    pool_order = ["PPE-MATH", "PPE-MMLU-Pro", "RB2"]
    cells_by_pool: dict[str, list[dict[str, Any]]] = {}
    pool_metadata: dict[str, Any] = {}

    for pool_name in pool_order:
        judges = sorted(pools[pool_name].keys())
        base_rows = pools[pool_name][judges[0]]
        base_keys = [(r[0], r[1]) for r in base_rows]
        gold = np.array([r[2] for r in base_rows], dtype=np.int64)
        n_items = len(gold)
        n_correct = int(gold.sum())
        n_prompts = len({r[0] for r in base_rows})

        for j in judges[1:]:
            assert [(r[0], r[1]) for r in pools[pool_name][j]] == base_keys, f"Key order mismatch in {pool_name}/{j}"

        cells: list[dict[str, Any]] = []
        for q in (0.2, 0.3):
            k = int(round(q * n_items))
            q_eff = k / n_items
            selected: dict[str, np.ndarray] = {}
            for j in judges:
                scores = np.array([r[3] for r in pools[pool_name][j]], dtype=np.float64)
                top_idx = np.argsort(-scores, kind="mergesort")[:k]
                mask = np.zeros(n_items, dtype=bool)
                mask[top_idx] = True
                selected[j] = mask

            for ja, jb in itertools.combinations(judges, 2):
                mask_a = selected[ja]
                mask_b = selected[jb]
                p_ab_unlab = float((mask_a & mask_b).sum()) / n_items
                lambda_unlab = p_ab_unlab / (q_eff * q_eff)
                unlab_excess = lambda_unlab - 1.0

                corr = gold == 1
                n_a_corr = int((mask_a & corr).sum())
                n_b_corr = int((mask_b & corr).sum())
                n_ab_corr = int((mask_a & mask_b & corr).sum())
                n_union_corr = int(((mask_a | mask_b) & corr).sum())

                p_a = n_a_corr / n_correct
                p_b = n_b_corr / n_correct
                p_ab = n_ab_corr / n_correct
                cov_cond = p_ab - (p_a * p_b)
                psi_cond = cov_cond / (p_a * p_b)

                r_true = n_union_corr / n_correct
                n_lp = (n_a_corr * n_b_corr) / n_ab_corr
                r_lp = n_union_corr / n_lp
                lp_gap = r_lp - r_true
                identity_err = abs(lp_gap - r_true * psi_cond)

                cells.append(
                    {
                        "pool": pool_name,
                        "q": q,
                        "k": k,
                        "q_eff": q_eff,
                        "judge_a": ja,
                        "judge_b": jb,
                        "lambda_unlab": lambda_unlab,
                        "unlab_excess": unlab_excess,
                        "psi_cond": psi_cond,
                        "true_union_recall": r_true,
                        "lp_union_recall": r_lp,
                        "lp_gap": lp_gap,
                        "n_lp": n_lp,
                        "n_union_corr": n_union_corr,
                        "identity_error": identity_err,
                    }
                )

        cells_by_pool[pool_name] = cells
        pool_metadata[pool_name] = {
            "n_judges": len(judges),
            "judges": judges,
            "n_items": n_items,
            "n_prompts": n_prompts,
            "n_gold_correct": n_correct,
            "n_cells": len(cells),
        }

    all_cells = [c for p in pool_order for c in cells_by_pool[p]]
    assert len(all_cells) == 324, f"Expected 324 cells, got {len(all_cells)}"

    max_identity_error = max(c["identity_error"] for c in all_cells)
    gate_lp_id_pass = bool(max_identity_error <= 1e-12)

    # Fit origin-constrained least-squares alpha_hat on PPE-MATH (156 cells) ONLY
    x_train = np.array([c["unlab_excess"] for c in cells_by_pool["PPE-MATH"]], dtype=np.float64)
    y_train = np.array([c["psi_cond"] for c in cells_by_pool["PPE-MATH"]], dtype=np.float64)
    alpha_hat = float(np.dot(x_train, y_train) / np.dot(x_train, x_train))

    eval_by_pool: dict[str, Any] = {}
    for pool_name in pool_order:
        cells = cells_by_pool[pool_name]
        lp_gaps = np.array([c["lp_gap"] for c in cells], dtype=np.float64)
        adj_gaps_list: list[float] = []
        adj_recalls_list: list[float] = []
        for c in cells:
            scale = max(0.25, 1.0 + alpha_hat * c["unlab_excess"])
            n_adj = c["n_lp"] * scale
            r_adj = min(1.0, c["n_union_corr"] / n_adj)
            adj_recalls_list.append(r_adj)
            adj_gaps_list.append(r_adj - c["true_union_recall"])
        adj_gaps = np.array(adj_gaps_list, dtype=np.float64)
        rmse_lp = float(np.sqrt(np.mean(lp_gaps * lp_gaps)))
        rmse_adj = float(np.sqrt(np.mean(adj_gaps * adj_gaps)))
        rel_rmse_change = float((rmse_adj - rmse_lp) / rmse_lp)
        eval_by_pool[pool_name] = {
            "n_cells": len(cells),
            "in_sample_calibration": pool_name == "PPE-MATH",
            "rmse_lp_gap": rmse_lp,
            "rmse_adj_gap": rmse_adj,
            "rel_rmse_change": rel_rmse_change,
            "mae_lp_gap": float(np.mean(np.abs(lp_gaps))),
            "mae_adj_gap": float(np.mean(np.abs(adj_gaps))),
            "mean_lp_gap": float(np.mean(lp_gaps)),
            "mean_adj_gap": float(np.mean(adj_gaps)),
            "frac_lp_overstates": float(np.mean(lp_gaps > 0.0)),
        }

    mmlu_clause = eval_by_pool["PPE-MMLU-Pro"]["rel_rmse_change"] <= -0.25
    rb2_clause = eval_by_pool["RB2"]["rmse_adj_gap"] <= eval_by_pool["RB2"]["rmse_lp_gap"]
    h1_pass = bool(gate_lp_id_pass and mmlu_clause and rb2_clause)

    return {
        "total_cells": len(all_cells),
        "pool_metadata": pool_metadata,
        "max_abs_identity_error": max_identity_error,
        "gate_lp_id_pass": gate_lp_id_pass,
        "alpha_hat_ppe_math": alpha_hat,
        "pool_evaluations": eval_by_pool,
        "h1_clauses": {
            "gate_lp_id_le_1e_12": gate_lp_id_pass,
            "ppe_mmlu_pro_rel_rmse_le_neg_0p25": bool(mmlu_clause),
            "rb2_rmse_non_worsening": bool(rb2_clause),
        },
        "h1_verdict": "PASS" if h1_pass else "FAIL",
    }


# ---------------------------------------------------------------------------
# C2 (H2): Provenance & Surface-Scaffolding Asymmetry Inversion Map
# ---------------------------------------------------------------------------
def recompute_c2(
    manifest: dict[str, Any],
    labels_frozen: list[dict[str, Any]],
    rb1_parquet: Path,
    rb2_parquet: Path,
    w1_jsonl: Path,
    w2_jsonl: Path,
    model_rows: dict[str, list[dict[str, Any]]],
) -> dict[str, Any]:
    # Load parquets into SHA256 lookup and RB1 math-prm dictionary
    sha_to_text: dict[str, str] = {}
    rb1_table = pq.read_table(rb1_parquet).to_pydict()
    rb1_math_prm: dict[str, dict[str, Any]] = {}
    for i in range(len(rb1_table["id"])):
        c_txt = rb1_table["chosen"][i]
        r_txt = rb1_table["rejected"][i]
        sha_to_text[hashlib.sha256(c_txt.encode("utf-8")).hexdigest()] = c_txt
        sha_to_text[hashlib.sha256(r_txt.encode("utf-8")).hexdigest()] = r_txt
        if rb1_table["subset"][i] == "math-prm":
            rb1_math_prm[str(rb1_table["id"][i])] = {
                "chosen": c_txt,
                "rejected": r_txt,
                "chosen_model": rb1_table["chosen_model"][i],
                "rejected_model": rb1_table["rejected_model"][i],
            }

    rb2_table = pq.read_table(rb2_parquet).to_pydict()
    for cl, rl in zip(rb2_table["chosen"], rb2_table["rejected"]):
        for x in (cl if isinstance(cl, list) else [cl]):
            sha_to_text[hashlib.sha256(x.encode("utf-8")).hexdigest()] = x
        for x in (rl if isinstance(rl, list) else [rl]):
            sha_to_text[hashlib.sha256(x.encode("utf-8")).hexdigest()] = x

    # Verify independent scaffolding_score against all 480 C2 items + 48 C3 items in manifest
    max_scaff_diff = 0.0
    n_verified = 0
    for row in manifest["c2_pairs"]:
        sc_c = scaffolding_score(sha_to_text[row["chosen_sha256"]])
        sc_r = scaffolding_score(sha_to_text[row["rejected_sha256"]])
        max_scaff_diff = max(
            max_scaff_diff,
            abs(sc_c - float(row["scaffolding_chosen"])),
            abs(sc_r - float(row["scaffolding_rejected"])),
            abs((sc_c - sc_r) - float(row["delta_scaffolding"])),
        )
        n_verified += 2
    for row in manifest["c3_rows"]:
        sc_o = scaffolding_score(sha_to_text[row["original_sha256"]])
        max_scaff_diff = max(max_scaff_diff, abs(sc_o - float(row["scaffolding_score"])))
        n_verified += 1

    # C2-Retained: 285 reference_disagreement RB1 math-prm pairs on W1 and W2
    labels_by_pid: dict[str, dict[int, dict[str, Any]]] = defaultdict(dict)
    for r in labels_frozen:
        labels_by_pid[str(r["prompt_id"])][int(r["completion_idx"])] = r
    rd_pids = sorted(
        [pid for pid, d in labels_by_pid.items() if d[1]["classification"] == "reference_disagreement"],
        key=lambda x: int(x),
    )
    assert len(rd_pids) == 285, f"Expected 285 reference_disagreement pairs, got {len(rd_pids)}"

    provenance_human_vs_gpt4 = sum(
        1
        for d in rb1_math_prm.values()
        if d["chosen_model"] == "human" and d["rejected_model"] == "GPT-4"
    )

    rd_pairs_sorted = sorted(
        [
            (
                scaffolding_score(rb1_math_prm[pid]["chosen"])
                - scaffolding_score(rb1_math_prm[pid]["rejected"]),
                pid,
            )
            for pid in rd_pids
        ],
        key=lambda x: (x[0], int(x[1])),
    )
    assert len(rd_pairs_sorted) == 285

    retained_results: dict[str, Any] = {}
    for jname, jpath in [("W1", w1_jsonl), ("W2", w2_jsonl)]:
        raw = [json.loads(line) for line in jpath.read_text(encoding="utf-8").splitlines() if line.strip()]
        by_key = {(str(r["prompt_id"]), int(r["completion_idx"])): r for r in raw}
        wins = []
        win_bounds_lo = []
        win_bounds_hi = []
        for delta_s, pid in rd_pairs_sorted:
            r0, r1 = by_key[(pid, 0)], by_key[(pid, 1)]
            iv0 = conditional_yes_bounds_from_mass(r0["p_yes"], r0["p_no"], 1.0 - r0["p_yes"] - r0["p_no"])
            iv1 = conditional_yes_bounds_from_mass(r1["p_yes"], r1["p_no"], 1.0 - r1["p_yes"] - r1["p_no"])
            w_lo, w_hi = pair_win_interval(iv0, iv1)
            mid0 = 0.5 * (iv0[0] + iv0[1])
            mid1 = 0.5 * (iv1[0] + iv1[1])
            wins.append(midpoint_win(mid0, mid1))
            win_bounds_lo.append(w_lo)
            win_bounds_hi.append(w_hi)

        wins_arr = np.array(wins, dtype=np.float64)
        t1 = wins_arr[:95]
        t2 = wins_arr[95:190]
        t3 = wins_arr[190:285]
        diff_t3_t1 = float(t3.mean() - t1.mean())

        # Bootstrap B=2000, seed=20261123 over tertiles (independent tertile resampling and full-285 re-tertilization)
        rng_strat = np.random.default_rng(20261123)
        idx1 = rng_strat.integers(0, 95, size=(2000, 95))
        idx3 = rng_strat.integers(0, 95, size=(2000, 95))
        boot_diffs_strat = t3[idx3].mean(axis=1) - t1[idx1].mean(axis=1)
        ci_strat = np.percentile(boot_diffs_strat, [2.5, 97.5])

        rng_full = np.random.default_rng(20261123)
        deltas_arr = np.array([x[0] for x in rd_pairs_sorted], dtype=np.float64)
        full_idx = rng_full.integers(0, 285, size=(2000, 285))
        boot_diffs_retertile = []
        for b_idx in full_idx:
            ord_b = np.argsort(deltas_arr[b_idx], kind="mergesort")
            wb = wins_arr[b_idx][ord_b]
            boot_diffs_retertile.append(float(wb[190:285].mean() - wb[:95].mean()))
        ci_retertile = np.percentile(boot_diffs_retertile, [2.5, 97.5])

        retained_results[jname] = {
            "n_pairs": 285,
            "tertile_sizes": [95, 95, 95],
            "overall_win_rate": float(wins_arr.mean()),
            "pair_win_bounds": [float(np.mean(win_bounds_lo)), float(np.mean(win_bounds_hi))],
            "T1_win_rate": float(t1.mean()),
            "T2_win_rate": float(t2.mean()),
            "T3_win_rate": float(t3.mean()),
            "T3_minus_T1": diff_t3_t1,
            "T3_minus_T1_gt_0": bool(diff_t3_t1 > 0.0),
            "T3_minus_T1_ci95_stratified": [float(ci_strat[0]), float(ci_strat[1])],
            "T3_minus_T1_ci95_retertiled": [float(ci_retertile[0]), float(ci_retertile[1])],
        }

    # C2-Unseen: 4 slices x 4 models = 16 cells
    cells: dict[str, dict[str, Any]] = {}
    for m_key in ["M1", "M2", "M3", "M4"]:
        rows_c2 = [r for r in model_rows[m_key] if r["component"] == "C2"]
        assert len(rows_c2) == 480, f"Expected 480 C2 rows for {m_key}, got {len(rows_c2)}"
        cells[m_key] = {}

        for sl in C2_SLICES:
            sl_rows = [r for r in rows_c2 if r["slice"] == sl]
            assert len(sl_rows) == 120, f"Expected 120 rows for {m_key}/{sl}, got {len(sl_rows)}"
            by_pid: dict[str, dict[int, dict[str, Any]]] = defaultdict(dict)
            for r in sl_rows:
                by_pid[str(r["prompt_id"])][int(r["completion_idx"])] = r
            assert len(by_pid) == 60

            # Preserve manifest pair order for deterministic bootstrap
            manifest_sl_pids = [str(p["prompt_id"]) for p in manifest["c2_pairs"] if p["slice"] == sl]
            assert len(manifest_sl_pids) == 60

            w_lo_list: list[float] = []
            w_hi_list: list[float] = []
            w_mid_score_list: list[float] = []
            w_mid_bounds_list: list[float] = []
            pos_scores: list[float] = []
            neg_scores: list[float] = []

            for pid in manifest_sl_pids:
                r0 = by_pid[pid][0]
                r1 = by_pid[pid][1]
                iv0 = (float(r0["conditional_yes_interval"][0]), float(r0["conditional_yes_interval"][1]))
                iv1 = (float(r1["conditional_yes_interval"][0]), float(r1["conditional_yes_interval"][1]))
                w_lo, w_hi = pair_win_interval(iv0, iv1)
                mid0 = 0.5 * (iv0[0] + iv0[1])
                mid1 = 0.5 * (iv1[0] + iv1[1])
                w_lo_list.append(w_lo)
                w_hi_list.append(w_hi)
                w_mid_score_list.append(midpoint_win(mid0, mid1))
                w_mid_bounds_list.append(0.5 * (w_lo + w_hi))
                pos_scores.append(mid0)
                neg_scores.append(mid1)

            w_mid_arr = np.array(w_mid_score_list, dtype=np.float64)
            ci_lo, ci_hi = bootstrap_mean_ci(w_mid_arr, n_boot=2000, seed=20261123)

            dec_counts = Counter(r["generated_decision"] for r in sl_rows)
            n_yes = int(dec_counts.get("yes", 0))
            n_no = int(dec_counts.get("no", 0))
            n_other = int(len(sl_rows) - n_yes - n_no)
            yn_correct = sum(
                1
                for r in sl_rows
                if (r["generated_decision"] == "yes" and int(r["gold"]) == 1)
                or (r["generated_decision"] == "no" and int(r["gold"]) == 0)
            )

            cells[m_key][sl] = {
                "n_pairs": 60,
                "n_items": 120,
                "pair_win_bounds": [float(np.mean(w_lo_list)), float(np.mean(w_hi_list))],
                "midpoint_pair_win_rate": float(w_mid_arr.mean()),
                "bounds_midpoint_pair_win_rate": float(np.mean(w_mid_bounds_list)),
                "bootstrap_ci95_2000": [ci_lo, ci_hi],
                "pooled_auroc": mann_whitney_auroc(pos_scores, neg_scores),
                "yes_count": n_yes,
                "no_count": n_no,
                "other_count": n_other,
                "yes_rate": float(n_yes / len(sl_rows)),
                "yn_correct": int(yn_correct),
                "yn_accuracy": float(yn_correct / len(sl_rows)),
            }

    # Evaluate pre-registered H2 decision rule on small BF16 judges M1 & M2, plus scale checks on M3 & M4
    h2_model_checks: dict[str, Any] = {}
    for m_key in ["M1", "M2"]:
        w_mp = cells[m_key]["rb1_math_prm_disjoint"]["midpoint_pair_win_rate"]
        w_rb2 = cells[m_key]["rb2_math_llm_vs_llm"]["midpoint_pair_win_rate"]
        w_hep = cells[m_key]["rb1_hep_python_sym"]["midpoint_pair_win_rate"]
        w_adv = cells[m_key]["rb1_llmbar_adver_asym"]["midpoint_pair_win_rate"]
        c1 = bool(w_rb2 > 0.50 and w_rb2 > w_mp)
        c2 = bool(w_hep >= 0.45 and w_hep > w_mp)
        c3 = bool(w_adv < 0.50)
        h2_model_checks[m_key] = {
            "clause1_rb2_math_gt_0p50_and_gt_mp": c1,
            "clause2_hep_ge_0p45_and_gt_mp": c2,
            "clause3_llmbar_adver_lt_0p50": c3,
            "model_pass": bool(c1 and c2 and c3),
        }

    scale_checks: dict[str, Any] = {}
    for m_key in ["M3", "M4"]:
        w_mp = cells[m_key]["rb1_math_prm_disjoint"]["midpoint_pair_win_rate"]
        w_adv = cells[m_key]["rb1_llmbar_adver_asym"]["midpoint_pair_win_rate"]
        scale_checks[m_key] = {
            "rb1_math_prm_disjoint_win_rate": w_mp,
            "rb1_math_prm_disjoint_gt_0p50": bool(w_mp > 0.50),
            "rb1_llmbar_adver_asym_win_rate": w_adv,
            "rb1_llmbar_adver_asym_gt_0p50": bool(w_adv > 0.50),
            "rescues_both_above_0p50": bool(w_mp > 0.50 and w_adv > 0.50),
        }

    h2_pass = bool(h2_model_checks["M1"]["model_pass"] and h2_model_checks["M2"]["model_pass"])

    return {
        "rb1_math_prm_total_pairs": len(rb1_math_prm),
        "rb1_math_prm_human_vs_gpt4_pairs": provenance_human_vs_gpt4,
        "manifest_scaffolding_items_verified": n_verified,
        "manifest_scaffolding_max_abs_diff": max_scaff_diff,
        "c2_retained_285": retained_results,
        "c2_unseen_cells": cells,
        "h2_small_model_checks": h2_model_checks,
        "c2_scale_behavior": scale_checks,
        "h2_verdict": "PASS" if h2_pass else "FAIL",
    }


# ---------------------------------------------------------------------------
# C3 (H3): 6 Checkpoints x 5 Arms Factorial, Quantization Parity & Decoupling
# ---------------------------------------------------------------------------
def recompute_c3(
    manifest: dict[str, Any],
    response_results: list[dict[str, Any]],
    model_rows: dict[str, list[dict[str, Any]]],
) -> dict[str, Any]:
    c3_pids = sorted({str(r["prompt_id"]) for r in manifest["c3_rows"]}, key=lambda x: int(x))
    assert len(c3_pids) == 24

    # Assemble uniform item lookup: checkpoint -> arm -> prompt_id -> completion_idx -> record
    checkpoints: dict[str, dict[str, dict[str, dict[int, dict[str, Any]]]]] = {
        k: {arm: defaultdict(dict) for arm in C3_ARMS}
        for k in ["W1", "W2", "M1", "M2", "M3", "M4"]
    }

    for r in response_results:
        j = str(r["judge"])
        if j in ("W1", "W2"):
            ci = int(r["completion_idx"])
            checkpoints[j][str(r["arm"])][str(r["prompt_id"])][ci] = {
                "conditional_yes_interval": (
                    float(r["conditional_yes_interval"][0]),
                    float(r["conditional_yes_interval"][1]),
                ),
                "generated_decision": str(r["generated_decision"]),
                "gold": 1 if ci == 0 else 0,
            }

    for m_key in ["M1", "M2", "M3", "M4"]:
        rows_c3 = [r for r in model_rows[m_key] if r["component"] == "C3"]
        assert len(rows_c3) == 240, f"Expected 240 C3 rows for {m_key}, got {len(rows_c3)}"
        for r in rows_c3:
            ci = int(r["completion_idx"])
            checkpoints[m_key][str(r["arm"])][str(r["prompt_id"])][ci] = {
                "conditional_yes_interval": (
                    float(r["conditional_yes_interval"][0]),
                    float(r["conditional_yes_interval"][1]),
                ),
                "generated_decision": str(r["generated_decision"]),
                "gold": int(r["gold"]),
            }

    # Pre-draw joint question-bootstrap index matrix (B=5000, N=24, seed=20261117)
    rng = np.random.default_rng(20261117)
    boot_q_idx = rng.integers(0, 24, size=(5000, 24))

    per_checkpoint: dict[str, Any] = {}
    for ckpt in ["W1", "W2", "M1", "M2", "M3", "M4"]:
        arm_stats: dict[str, Any] = {}
        arm_pair_lo: dict[str, np.ndarray] = {}
        arm_pair_hi: dict[str, np.ndarray] = {}
        arm_pair_mid: dict[str, np.ndarray] = {}

        for arm in C3_ARMS:
            w_lo_list: list[float] = []
            w_hi_list: list[float] = []
            w_mid_list: list[float] = []
            pos_scores: list[float] = []
            neg_scores: list[float] = []
            items_flat: list[dict[str, Any]] = []

            for pid in c3_pids:
                r0 = checkpoints[ckpt][arm][pid][0]
                r1 = checkpoints[ckpt][arm][pid][1]
                iv0 = r0["conditional_yes_interval"]
                iv1 = r1["conditional_yes_interval"]
                w_lo, w_hi = pair_win_interval(iv0, iv1)
                mid0 = 0.5 * (iv0[0] + iv0[1])
                mid1 = 0.5 * (iv1[0] + iv1[1])
                w_lo_list.append(w_lo)
                w_hi_list.append(w_hi)
                w_mid_list.append(midpoint_win(mid0, mid1))
                pos_scores.append(mid0)
                neg_scores.append(mid1)
                items_flat.extend([r0, r1])

            arm_pair_lo[arm] = np.array(w_lo_list, dtype=np.float64)
            arm_pair_hi[arm] = np.array(w_hi_list, dtype=np.float64)
            arm_pair_mid[arm] = np.array(w_mid_list, dtype=np.float64)

            boot_arm_means = arm_pair_mid[arm][boot_q_idx].mean(axis=1)
            arm_ci = np.percentile(boot_arm_means, [2.5, 97.5])

            decs = Counter(it["generated_decision"] for it in items_flat)
            n_yes = int(decs.get("yes", 0))
            n_no = int(decs.get("no", 0))
            n_other = int(48 - n_yes - n_no)
            yn_corr = sum(
                1
                for it in items_flat
                if (it["generated_decision"] == "yes" and it["gold"] == 1)
                or (it["generated_decision"] == "no" and it["gold"] == 0)
            )
            tpr_yes = sum(1 for it in items_flat if it["gold"] == 1 and it["generated_decision"] == "yes")
            tnr_no = sum(1 for it in items_flat if it["gold"] == 0 and it["generated_decision"] == "no")

            arm_stats[arm] = {
                "n_pairs": 24,
                "n_items": 48,
                "pair_win_count_midpoint": float(arm_pair_mid[arm].sum()),
                "pair_win_bounds": [float(arm_pair_lo[arm].mean()), float(arm_pair_hi[arm].mean())],
                "midpoint_pair_win_rate": float(arm_pair_mid[arm].mean()),
                "bootstrap_ci95_5000": [float(arm_ci[0]), float(arm_ci[1])],
                "pooled_auroc": mann_whitney_auroc(pos_scores, neg_scores),
                "yes_count": n_yes,
                "no_count": n_no,
                "other_count": n_other,
                "yes_rate": float(n_yes / 48.0),
                "yn_correct": int(yn_corr),
                "yn_accuracy": float(yn_corr / 48.0),
                "gold1_yes_count": int(tpr_yes),
                "gold0_no_count": int(tnr_no),
            }

        contrasts: dict[str, Any] = {}
        for arm_x, arm_y in C3_CONTRASTS:
            cname = f"{arm_x}_minus_{arm_y}"
            d_lo = float((arm_pair_lo[arm_x] - arm_pair_hi[arm_y]).mean())
            d_hi = float((arm_pair_hi[arm_x] - arm_pair_lo[arm_y]).mean())
            d_vec = arm_pair_mid[arm_x] - arm_pair_mid[arm_y]
            d_mid = float(d_vec.mean())
            boot_d = d_vec[boot_q_idx].mean(axis=1)
            ci_lo, ci_hi = np.percentile(boot_d, [2.5, 97.5])
            contrasts[cname] = {
                "interval_bounds": [d_lo, d_hi],
                "midpoint_diff": d_mid,
                "bootstrap_ci95_5000": [float(ci_lo), float(ci_hi)],
            }

        # Ranking-vs-decision decoupling summaries (RS -> RA and O -> A)
        decoupling = {}
        for src_arm, dst_arm in [("RS", "RA"), ("O", "A")]:
            d_win = arm_stats[dst_arm]["midpoint_pair_win_rate"] - arm_stats[src_arm]["midpoint_pair_win_rate"]
            d_acc = arm_stats[dst_arm]["yn_accuracy"] - arm_stats[src_arm]["yn_accuracy"]
            d_yes = arm_stats[dst_arm]["yes_rate"] - arm_stats[src_arm]["yes_rate"]
            decoupling[f"{src_arm}_to_{dst_arm}"] = {
                "delta_pair_win_rate": float(d_win),
                "delta_yn_accuracy": float(d_acc),
                "delta_yes_rate": float(d_yes),
                "win_up_or_flat_while_yn_acc_down": bool(d_win >= 0.0 and d_acc < 0.0),
                "strict_win_up_while_yn_acc_down": bool(d_win > 0.0 and d_acc < 0.0),
            }

        per_checkpoint[ckpt] = {
            "arms": arm_stats,
            "contrasts": contrasts,
            "decoupling": decoupling,
        }

    # Quantization parity check: M1 (Qwen2.5-1.5B BF16) vs W1 (Qwen2.5-1.5B Q4_K_M)
    m1_o_win = per_checkpoint["M1"]["arms"]["O"]["midpoint_pair_win_rate"]
    w1_o_win = per_checkpoint["W1"]["arms"]["O"]["midpoint_pair_win_rate"]
    m1_a_yes = per_checkpoint["M1"]["arms"]["A"]["yes_rate"]
    w1_a_yes = per_checkpoint["W1"]["arms"]["A"]["yes_rate"]
    decision_agree_240 = sum(
        1
        for arm in C3_ARMS
        for pid in c3_pids
        for ci in (0, 1)
        if checkpoints["M1"][arm][pid][ci]["generated_decision"]
        == checkpoints["W1"][arm][pid][ci]["generated_decision"]
    )
    quantization_parity = {
        "W1_arm_O_win_rate": w1_o_win,
        "M1_arm_O_win_rate": m1_o_win,
        "M1_reproduces_arm_O_reversal_lt_0p50": bool(m1_o_win < 0.50),
        "W1_arm_A_yes_rate": w1_a_yes,
        "M1_arm_A_yes_rate": m1_a_yes,
        "M1_reproduces_arm_A_rejection_le_0p15": bool(m1_a_yes <= 0.15),
        "decision_agreement_240_items": int(decision_agree_240),
        "decision_agreement_rate": float(decision_agree_240 / 240.0),
        "quantization_parity_confirmed": bool(m1_o_win < 0.50 and m1_a_yes <= 0.15),
    }

    # H3 Scale Decoupling Test on M3 (4B) and M4 (7B)
    scale_checks: dict[str, Any] = {}
    for m_key in ["M3", "M4"]:
        rs_win = per_checkpoint[m_key]["arms"]["RS"]["midpoint_pair_win_rate"]
        ra_yes = per_checkpoint[m_key]["arms"]["RA"]["yes_rate"]
        ra_acc = per_checkpoint[m_key]["arms"]["RA"]["yn_accuracy"]
        c_rs = bool(rs_win >= 0.90)
        c_ra = bool(ra_yes >= 0.40 and ra_acc >= 0.75)
        scale_checks[m_key] = {
            "RS_pair_win_rate": rs_win,
            "RS_eliminates_rationale_interference_ge_0p90": c_rs,
            "RA_yes_rate": ra_yes,
            "RA_yn_accuracy": ra_acc,
            "RA_cures_bare_answer_rejection": c_ra,
            "passes_both_scale_clauses": bool(c_rs and c_ra),
        }

    h3_both_cure_all = bool(
        scale_checks["M3"]["passes_both_scale_clauses"]
        and scale_checks["M4"]["passes_both_scale_clauses"]
    )

    return {
        "checkpoints": per_checkpoint,
        "quantization_parity_M1_vs_W1": quantization_parity,
        "h3_scale_checks": scale_checks,
        "h3_both_4b_and_7b_cure_both_modes": h3_both_cure_all,
    }


# ---------------------------------------------------------------------------
# C4: Safe vs Naive Floating-Point Poolwise Centering Stability Audit
# ---------------------------------------------------------------------------
def center_pool_naive(r: np.ndarray) -> np.ndarray:
    v = np.full(len(r), 1.0 / len(r), dtype=np.float64)
    return r - float(np.sum(v * r))


def center_pool_safe(r: np.ndarray) -> np.ndarray:
    v = np.full(len(r), 1.0 / len(r), dtype=np.float64)
    r_max = float(np.max(r))
    return (r - r_max) + float(np.sum(v * (r_max - r)))


def poolwise_u_alpha_from_centered(centered_pools: list[np.ndarray], alpha: float = 0.3) -> float:
    z = np.concatenate(centered_pools)
    n = len(z)
    z_sorted = np.sort(z)[::-1]
    m = alpha * n
    k_full = int(math.floor(m))
    rem = m - k_full
    total = float(np.sum(z_sorted[:k_full]))
    if rem > 0.0 and k_full < n:
        total += rem * float(z_sorted[k_full])
    return float(total / m)


def count_within_prompt_ties(pools: list[np.ndarray]) -> int:
    total = 0
    for a in pools:
        total += int(np.triu(a[:, None] == a[None, :], k=1).sum())
    return total


def count_pooled_ties(pools: list[np.ndarray]) -> int:
    z = np.concatenate(pools)
    counts = Counter(z.tolist())
    return int(sum(c * (c - 1) // 2 for c in counts.values()))


def recompute_c4(items_csv_gz: Path) -> dict[str, Any]:
    series_prompts: dict[tuple[str, str], dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))
    with gzip.open(items_csv_gz, "rt", encoding="utf-8") as f:
        for row in csv.DictReader(f):
            if row["judge_id"] == "V0":
                continue
            series_prompts[(row["pool"], row["judge_id"])][str(row["prompt_id"])].append(float(row["score"]))

    assert len(series_prompts) == 30, f"Expected 30 RM series, got {len(series_prompts)}"

    # Build ordered list-of-arrays for the 30 RM series + 0.5-step discrete rubric series on PPE-MATH
    rm_series: list[tuple[str, list[np.ndarray]]] = []
    rubric_series: list[tuple[str, list[np.ndarray]]] = []
    for (pool_name, judge_id), pdict in sorted(series_prompts.items()):
        pools = [np.array(sc, dtype=np.float64) for _, sc in sorted(pdict.items())]
        rm_series.append((f"{pool_name}:{judge_id}", pools))
        if pool_name == "PPE-MATH":
            rubric_pools = [np.round(a * 2.0) / 2.0 for a in pools]
            rubric_series.append((f"PPE-MATH-rubric0p5:{judge_id}", rubric_pools))

    # Synthetic Proposition 1 check at x = 1 - 2^-53 (n=3 uniform pool)
    x_near_one = 1.0 - 2.0**-53
    prop1_pool = np.full(3, x_near_one, dtype=np.float64)
    prop1_naive = center_pool_naive(prop1_pool)
    prop1_safe = center_pool_safe(prop1_pool)

    offsets = [0.0, 1e4, 1e8, 1e12, 1e15]
    by_offset_rm: dict[str, Any] = {}
    by_offset_rubric: dict[str, Any] = {}

    for group_name, group_list, target_dict in [
        ("rm_30_series", rm_series, by_offset_rm),
        ("ppe_math_0p5_rubric", rubric_series, by_offset_rubric),
    ]:
        # Precompute C=0 reference centered pools with safe centering
        ref_safe_by_series = {
            sname: [center_pool_safe(a) for a in pools] for sname, pools in group_list
        }

        for c_val in offsets:
            c_key = f"{c_val:.0e}" if c_val > 0 else "0"
            max_u03_diff = 0.0
            mean_u03_diff_acc: list[float] = []
            max_pointwise_diff = 0.0
            wp_tie_mismatch_naive_vs_c0 = 0
            wp_tie_mismatch_safe_vs_c0 = 0
            pooled_tie_pairs_c0 = 0
            pooled_tie_pairs_naive = 0
            pooled_tie_pairs_safe = 0
            zero_items_c0 = 0
            zero_items_naive = 0
            zero_items_safe = 0
            top03_symdiff_total = 0

            for sname, base_pools in group_list:
                ref_safe = ref_safe_by_series[sname]
                shifted_pools = [
                    a + (float(c_val) + float(idx) if c_val > 0.0 else 0.0)
                    for idx, a in enumerate(base_pools)
                ]
                naive_centered = [center_pool_naive(r) for r in shifted_pools]
                safe_centered = [center_pool_safe(r) for r in shifted_pools]

                u_naive = poolwise_u_alpha_from_centered(naive_centered, alpha=0.3)
                u_safe = poolwise_u_alpha_from_centered(safe_centered, alpha=0.3)
                u_diff = abs(u_safe - u_naive)
                max_u03_diff = max(max_u03_diff, u_diff)
                mean_u03_diff_acc.append(u_diff)

                z_ref = np.concatenate(ref_safe)
                z_naive = np.concatenate(naive_centered)
                z_safe = np.concatenate(safe_centered)
                max_pointwise_diff = max(max_pointwise_diff, float(np.max(np.abs(z_safe - z_naive))))

                for a0, zn, zs in zip(base_pools, naive_centered, safe_centered):
                    eq0 = np.triu(a0[:, None] == a0[None, :], k=1)
                    eqn = np.triu(zn[:, None] == zn[None, :], k=1)
                    eqs = np.triu(zs[:, None] == zs[None, :], k=1)
                    wp_tie_mismatch_naive_vs_c0 += int((eq0 != eqn).sum())
                    wp_tie_mismatch_safe_vs_c0 += int((eq0 != eqs).sum())

                pooled_tie_pairs_c0 += count_pooled_ties(ref_safe)
                pooled_tie_pairs_naive += count_pooled_ties(naive_centered)
                pooled_tie_pairs_safe += count_pooled_ties(safe_centered)
                zero_items_c0 += int((z_ref == 0.0).sum())
                zero_items_naive += int((z_naive == 0.0).sum())
                zero_items_safe += int((z_safe == 0.0).sum())

                k_top = int(round(0.3 * len(z_safe)))
                top_n = set(np.argsort(-z_naive, kind="mergesort")[:k_top].tolist())
                top_s = set(np.argsort(-z_safe, kind="mergesort")[:k_top].tolist())
                top03_symdiff_total += len(top_n ^ top_s)

            target_dict[c_key] = {
                "offset_C": c_val,
                "n_series": len(group_list),
                "max_abs_u0p3_diff_safe_vs_naive": max_u03_diff,
                "mean_abs_u0p3_diff_safe_vs_naive": float(np.mean(mean_u03_diff_acc)),
                "max_pointwise_centered_diff": max_pointwise_diff,
                "within_prompt_tie_mismatches_vs_C0_naive": wp_tie_mismatch_naive_vs_c0,
                "within_prompt_tie_mismatches_vs_C0_safe": wp_tie_mismatch_safe_vs_c0,
                "zero_centered_count_C0": zero_items_c0,
                "zero_centered_count_naive": zero_items_naive,
                "zero_centered_count_safe": zero_items_safe,
                "pooled_tie_pairs_C0": pooled_tie_pairs_c0,
                "pooled_tie_pairs_naive": pooled_tie_pairs_naive,
                "pooled_tie_pairs_safe": pooled_tie_pairs_safe,
                "top0p3_selection_symdiff_total": top03_symdiff_total,
            }

    return {
        "proposition1_near_one_check": {
            "x": x_near_one,
            "pool_size": 3,
            "naive_residual_abs": float(np.max(np.abs(prop1_naive))),
            "safe_residual_abs": float(np.max(np.abs(prop1_safe))),
            "naive_breaks_zero_tie": bool(np.any(prop1_naive != 0.0)),
            "safe_preserves_exact_zero": bool(np.all(prop1_safe == 0.0)),
        },
        "rm_30_series_by_offset": by_offset_rm,
        "ppe_math_0p5_rubric_by_offset": by_offset_rubric,
    }


def main() -> None:
    parser = argparse.ArgumentParser(description="Independent blind recomputation for #57 flagship audit.")
    parser.add_argument(
        "--data-dir",
        type=Path,
        required=True,
        help="Directory containing pinned rb1_filtered.parquet and rb2_test.parquet.",
    )
    parser.add_argument(
        "--repo-root",
        type=Path,
        default=Path(__file__).resolve().parents[4],
        help="Repository root directory.",
    )
    parser.add_argument(
        "--out",
        type=Path,
        default=Path(__file__).resolve().parent / "RECOMPUTED.json",
        help="Output JSON path.",
    )
    args = parser.parse_args()

    repo_root = args.repo_root.resolve()
    audit_dir = repo_root / "scout" / "repro" / "20261123-judge-flagship-audit"
    data_dir = args.data_dir.resolve()

    rb1_parquet = data_dir / "rb1_filtered.parquet"
    rb2_parquet = data_dir / "rb2_test.parquet"
    items_csv_gz = (
        repo_root
        / "runs"
        / "2026-11-14-0921-box"
        / "judge-table"
        / "cells"
        / "withinprompt-bestofk-20261113"
        / "items.csv.gz"
    )
    labels_frozen_path = (
        repo_root / "reviews" / "2026-11-14-judge-mismatch-prevalence" / "agent" / "LABELS_FROZEN.json"
    )
    response_results_path = (
        repo_root / "reviews" / "2026-11-15-judge-answer-vs-rationale" / "agent" / "RESPONSE_RESULTS.json"
    )
    w1_jsonl = (
        repo_root
        / "runs"
        / "2026-11-14-0921-box"
        / "judge-table"
        / "cells"
        / "C1-debate-lite-harness"
        / "inputs"
        / "rb1mp__W1.jsonl"
    )
    w2_jsonl = (
        repo_root
        / "runs"
        / "2026-11-14-0921-box"
        / "judge-table"
        / "cells"
        / "C1-debate-lite-harness"
        / "inputs"
        / "rb1mp__W2.jsonl"
    )
    manifest_path = audit_dir / "out" / "INPUT_MANIFEST.json"

    actual_sha = {
        "rb1_filtered_parquet": sha256_file(rb1_parquet),
        "rb2_test_parquet": sha256_file(rb2_parquet),
        "items_csv_gz": sha256_file(items_csv_gz),
        "labels_frozen_json": sha256_file(labels_frozen_path),
        "input_manifest_json": sha256_file(manifest_path),
        "response_results_json": sha256_file(response_results_path),
        "rb1mp_W1_jsonl": sha256_file(w1_jsonl),
        "rb1mp_W2_jsonl": sha256_file(w2_jsonl),
    }
    for key, exp in EXPECTED_SHA256.items():
        assert actual_sha[key] == exp, f"SHA256 mismatch on {key}: {actual_sha[key]} != {exp}"

    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    labels_frozen = json.loads(labels_frozen_path.read_text(encoding="utf-8"))
    response_results = json.loads(response_results_path.read_text(encoding="utf-8"))

    model_rows: dict[str, list[dict[str, Any]]] = {}
    model_gates: dict[str, Any] = {}
    for m_key, fname in MODEL_SCORE_FILES.items():
        fpath = audit_dir / "out" / fname
        actual_sha[fname] = sha256_file(fpath)
        payload = json.loads(fpath.read_text(encoding="utf-8"))
        assert payload["manifest_sha256"] == EXPECTED_SHA256["input_manifest_json"]
        assert payload["main_calls"] == 720
        assert payload["identity_calls"] == 16
        assert payload["identity_gate_pass"] is True
        rows = payload["rows"]
        # Independently verify conditional_yes_interval from observed probabilities + omitted mass
        max_iv_err = 0.0
        for r in rows:
            lo_p, hi_p = conditional_yes_bounds_from_mass(
                r["p_yes_observed"], r["p_no_observed"], r["omitted_mass"]
            )
            max_iv_err = max(
                max_iv_err,
                abs(lo_p - float(r["conditional_yes_interval"][0])),
                abs(hi_p - float(r["conditional_yes_interval"][1])),
            )
        model_rows[m_key] = rows
        model_gates[m_key] = {
            "file": f"out/{fname}",
            "sha256": actual_sha[fname],
            "judge": payload["judge"],
            "params_b": payload["params_b"],
            "main_calls": int(payload["main_calls"]),
            "identity_calls": int(payload["identity_calls"]),
            "identity_max_diff": float(payload["identity_max_diff"]),
            "identity_gate_pass": bool(payload["identity_gate_pass"]),
            "max_interval_recompute_err": max_iv_err,
        }

    c1_out = recompute_c1(items_csv_gz)
    c2_out = recompute_c2(
        manifest=manifest,
        labels_frozen=labels_frozen,
        rb1_parquet=rb1_parquet,
        rb2_parquet=rb2_parquet,
        w1_jsonl=w1_jsonl,
        w2_jsonl=w2_jsonl,
        model_rows=model_rows,
    )
    c3_out = recompute_c3(
        manifest=manifest,
        response_results=response_results,
        model_rows=model_rows,
    )
    c4_out = recompute_c4(items_csv_gz)

    output_payload = {
        "protocol": "D-050 independent blind recomputation",
        "blind_status_at_generation": "Generated strictly prior to reading primary code/*.py, scout/checks/judge_diagnostics.py, out/c1_c4_offline.json, out/RESULTS.json, or RESULT.md",
        "pinned_sha256_verified": actual_sha,
        "model_score_gates": model_gates,
        "C1_H1": c1_out,
        "C2_H2": c2_out,
        "C3_H3": c3_out,
        "C4_centering_stability": c4_out,
    }

    args.out.parent.mkdir(parents=True, exist_ok=True)
    args.out.write_text(json.dumps(output_payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    print(f"Wrote {args.out.name} ({args.out.stat().st_size} bytes)")


if __name__ == "__main__":
    main()
