from __future__ import annotations

import itertools
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from wormhole_proof.core.wormhole_smooth import SmoothConfig, run_smooth_experiment

OUTPUT = Path("artifacts/hp_sweep_metrics.txt")
OUTPUT.parent.mkdir(parents=True, exist_ok=True)

magnitudes = [0.22, 0.24, 0.26, 0.28, 0.30, 0.32]
budget_fracs = [0.10, 0.08]
debt_rates = [0.03, 0.04]

lines = [
    "hp_mag\tbudget_frac\tdebt_rate\tthroughput\thp_match\thp_packets\tmargin_min\tbit0\tbit1\tbit2"
]

for mag, budget, debt in itertools.product(magnitudes, budget_fracs, debt_rates):
    cfg = SmoothConfig(
        hp_message_magnitude=mag,
        wormhole_budget_fraction=budget,
        debt_repay_rate=debt,
    )
    result = run_smooth_experiment(cfg, seed=7)
    m = result.metrics
    bit_acc = ["nan", "nan", "nan"]
    if result.geometry and result.geometry.hp_decode_bits:
        bit_array = result.geometry.hp_decode_bits
        if bit_array:
            cols = zip(*bit_array)
            bit_acc = [f"{sum(col)/len(bit_array):.3f}" for col in cols]

    lines.append(
        "\t".join(
            [
                f"{mag:.3f}",
                f"{budget:.3f}",
                f"{debt:.3f}",
                f"{m.throughput:.4f}",
                f"{m.hp_match:.3f}",
                str(m.hp_packets),
                f"{m.cfl_margin_min:.4f}",
                *bit_acc,
            ]
        )
    )

OUTPUT.write_text("\n".join(lines), encoding="utf-8")
print("Sweep written to", OUTPUT)
