"""Regenerate the hardware tables (II-VII) and the Fig. 3 data series.

Run directly:

    python reproduce_tables.py

Every number is recomputed from the event counts in `hardware_data.py` using
the estimators in `stats.py`, and printed next to the value reported in the
paper so discrepancies (rounding only) are obvious.
"""

from __future__ import annotations

import numpy as np

import data_io as hw          # CSV-backed loader (falls back to hardware_data)
from stats import (
    Interval,
    dc_dump_theory,
    fit_floor_gain,
    fmt_pct,
    pearson_fisher_ci,
    suppression_ratio,
    wilson_ci,
)


def _hr(title: str) -> None:
    print("\n" + "=" * 72)
    print(title)
    print("=" * 72)


def _ci_str(ci: Interval) -> str:
    return f"{ci.point:.4f} [{ci.low:.4f}, {ci.high:.4f}]"


def experiment_2() -> None:
    _hr("Experiment 2 - Neutral-state heralding (Table II)")
    print(f"{'Input':<24}{'n':>7}  {'p_hat (95% Wilson CI)':<28}{'expected'}")
    neutral_x = neutral_n = 0
    control = None
    for r in hw.EXP2:
        ci = wilson_ci(r.x, r.n)
        exp = "-" if r.expected is None else f"{r.expected:g}"
        print(f"{r.label:<24}{r.n:>7}  {_ci_str(ci):<28}{exp}")
        if r.kind == "neutral":
            neutral_x += r.x
            neutral_n += r.n
        if r.kind == "control":
            control = r
    pooled = wilson_ci(neutral_x, neutral_n)
    print(f"\nPooled neutral leakage: {fmt_pct(pooled.point)} "
          f"[{fmt_pct(pooled.low)}, {fmt_pct(pooled.high)}]  (paper: 0.6% [0.5%, 0.7%])")
    sup = suppression_ratio(control.x, control.n, neutral_x, neutral_n)
    print(f"Suppression vs control: {sup.point:.1f}x "
          f"[{sup.low:.1f}, {sup.high:.1f}]  (paper: 31.6x [27.2, 36.7])")


def experiment_3() -> None:
    _hr("Experiment 3 - Proportional error detection (Table III)")
    c = np.array(hw.EXP3_C)
    p_hw = np.array([r.x / r.n for r in hw.EXP3])
    theory = dc_dump_theory(c)
    print(f"{'c':>5}  {'theory':>8}  {'hardware (95% CI)':<26}")
    for ci_c, th, r in zip(c, theory, hw.EXP3):
        ci = wilson_ci(r.x, r.n)
        print(f"{ci_c:>5.2f}  {th:>8.3f}  {_ci_str(ci):<26}")
    p_floor, g = fit_floor_gain(c, p_hw)
    print(f"\nFloor+gain fit: p_floor = {p_floor:.3f}, g = {g:.2f}  "
          f"(paper: 0.010, 1.12)")
    r = pearson_fisher_ci(theory, p_hw)
    print(f"Pearson r = {r.point:.4f} [{r.low:.3f}, {r.high:.4f}]  "
          f"(paper: 0.9992 [0.994, 0.9999])")


def experiment_4() -> None:
    _hr("Experiment 4 - Neutral-sector unitary core (Table IV / Fig. 3)")
    print(f"{'Configuration':<22}{'n':>7}  {'p_hat (95% Wilson CI)'}")
    fig_rows = []
    control_1x = None
    neutral_3x = None
    for r in hw.EXP4:
        ci = wilson_ci(r.x, r.n)
        print(f"{r.label:<22}{r.n:>7}  {_ci_str(ci)}")
        if r.kind == "neutral":
            fig_rows.append((r.extra["depth"], ci))
        if r.label == "Control, 1x core":
            control_1x = r
        if r.label == "Neutral, 3x core":
            neutral_3x = r
    print("\nFig. 3 data (depth, p_hat, err+, err-):")
    for depth, ci in sorted(fig_rows):
        print(f"  {depth}  {ci.point:.4f}  "
              f"{ci.high - ci.point:.5f}  {ci.point - ci.low:.5f}")
    ratio = suppression_ratio(control_1x.x, control_1x.n,
                              neutral_3x.x, neutral_3x.n)
    print(f"\n1x control / 3x neutral ratio: {ratio.point:.0f} "
          f"[{ratio.low:.0f}, {ratio.high:.0f}]  "
          f"(paper: ~950 [2.4e2, 3.8e3])")


def experiment_5() -> None:
    _hr("Experiment 5A - Parity-checked-subspace heralding (Table V)")
    print(f"{'Basis state':<12}{'p_syn (95% CI)':<26}{'port':>5}{'fid':>8}")
    syn_x = syn_n = 0
    fids = []
    for r in hw.EXP5A:
        ci = wilson_ci(r.x, r.n)
        fid = r.extra["fidelity"]
        print(f"{r.label:<12}{_ci_str(ci):<26}{r.port:>5}{fmt_pct(fid,1):>8}")
        syn_x += r.x
        syn_n += r.n
        fids.append(fid)
    mean = wilson_ci(syn_x, syn_n)
    print(f"{'Mean':<12}{_ci_str(mean):<26}{'':>5}{fmt_pct(np.mean(fids),1):>8}"
          f"   (paper mean: 0.0232 [0.0218, 0.0248], 95.1%)")

    _hr("Experiment 5B - Selective parity detection (Table VI)")
    print(f"{'Input':<16}{'exp':>4}{'meas':>5}  {'selectivity (95% CI)'}")
    for r in hw.EXP5B:
        ci = wilson_ci(r.x, r.n)
        print(f"{r.label:<16}{r.extra['expected_port']:>4}{r.port:>5}  "
              f"{_ci_str(ci)}")

    _hr("Experiment 5C - Suppression ratio")
    ctrl = hw.EXP5C_CONTROL
    ctrl_ci = wilson_ci(ctrl.x, ctrl.n)
    print(f"Code-space mean syndrome leakage: {_ci_str(mean)}")
    print(f"Non-neutral control leakage:      {_ci_str(ctrl_ci)}")
    sup = suppression_ratio(ctrl.x, ctrl.n, syn_x, syn_n)
    print(f"Suppression ratio: {sup.point:.1f}x [{sup.low:.1f}, {sup.high:.1f}]  "
          f"(paper: 23.7x [22.2, 25.3])")


def experiment_6() -> None:
    _hr("Experiment 6 - Hong-Ou-Mandel control (Table VII)")
    print(f"{'Chip state':<20}{'HOM vis':>9}  {'dump prob (95% CI)'}")
    for r in hw.EXP6:
        ci = wilson_ci(r.x, r.n)
        vis = r.extra["hom_visibility"]
        tag = "~" if r.extra.get("hom_from_calibration_report") else " "
        print(f"{r.label:<20}{tag}{fmt_pct(vis,1):>8}  {_ci_str(ci)}")


def summary() -> None:
    _hr("Totals")
    print(f"Summed per-configuration events: {hw.total_events():,}")
    print("Conservative distinct total quoted in paper: > 340,000")


def main() -> None:
    experiment_2()
    experiment_3()
    experiment_4()
    experiment_5()
    experiment_6()
    summary()


if __name__ == "__main__":
    main()
