"""7-A: the boot's shape-pin sweep, reproduced per trial, with per-row timings and clocks.

Each trial: idle (--idle-s) so the card drops out of its serving state, then optionally
card_clocks.warm_to_serving, then the boot's own race (custom_op._time_family per family,
_PIN_MIN_RACES races, decide_family_across_races) at the shipped rows (1,16,32). Per family it
also times every row of --rows singly, so the rows the sweep never sees (33-64) are on record.
Each _time_family call is bracketed by clock reads; a read below the application clock that is not
boosted counts as a start-window sample.
Usage: python a7_pinsweep.py --model M --linears fc,layers.0.mlp.down_proj --trials 3 [--warm]
"""
import argparse
import json
import pathlib
import sys
import time

sys.path.insert(0, "/src")
import torch  # noqa: E402

from arbi_serve.engine import card_clocks as cc  # noqa: E402
from arbi_serve.weight_quant.exl3 import custom_op as co  # noqa: E402
from arbi_serve.weight_quant.exl3 import shim  # noqa: E402
from tools.exl3_largem_dispatch_bench import _load_linear  # noqa: E402
from tools.exl3_pin_record import _Inner  # noqa: E402

ap = argparse.ArgumentParser()
ap.add_argument("--model", action="append", required=True)
ap.add_argument("--linears", required=True)
ap.add_argument("--trials", type=int, default=3)
ap.add_argument("--warm", action="store_true")
ap.add_argument("--idle-s", type=float, default=20.0)
ap.add_argument("--rows", default="1,16,32,33,40,48,64")
ap.add_argument("--out", required=True)
a = ap.parse_args()
dev = "cuda:0"
shim.load_ext()
ext = co._exllamav3_ext()
inners = {}
for m in a.model:
    for p in a.linears.split(","):
        try:
            t = _load_linear(pathlib.Path(m), p, dev)
        except (Exception, SystemExit) as e:  # noqa: BLE001
            print(f"# {m}:{p} skipped {e}")
            continue
        i = _Inner(t)
        inners.setdefault(f"{i.in_features}x{i.out_features}xK{i.K}", i)
rows_extra = [int(r) for r in a.rows.split(",")]
out = []
for trial in range(a.trials):
    torch.cuda.synchronize()
    time.sleep(a.idle_s)
    c0 = cc.read_clocks(dev)
    warm = cc.warm_to_serving(dev) if a.warm else None
    rec = {"trial": trial, "warm": warm, "clock_start": c0, "geoms": {}}
    for geom, inner in sorted(inners.items()):
        in_f, out_f, k = inner.in_features, inner.out_features, inner.K
        legal = co.legal_shape_ladders(in_f, out_f, k, ext=ext)
        co.set_pin_select_rows((1, 16, 32))
        races, sw, n = [], 0, 0
        t0 = time.perf_counter()
        for _ in range(co._PIN_MIN_RACES):
            r = {}
            for fam, lad in legal.items():
                before = cc.read_clocks(dev)
                r[fam] = co._time_family(ext, inner, lad, in_f, out_f, dev)[0]
                after = cc.read_clocks(dev)
                for c in (before, after):
                    n += 1
                    sw += 0 if cc.boosted(c) else 1
            races.append(r)
        sweep_s = time.perf_counter() - t0
        v = co.decide_family_across_races(races)
        per_row = {}
        for fam, lad in legal.items():
            per_row[f"K{fam[0]}N{fam[1]}"] = {}
            for m in rows_extra:
                co.set_pin_select_rows((m,))
                per_row[f"K{fam[0]}N{fam[1]}"][m] = round(
                    co._time_family(ext, inner, lad, in_f, out_f, dev)[0] * 1e3, 1
                )
        co.set_pin_select_rows(None)
        rec["geoms"][geom] = {
            "verdict": {"family": f"K{v.family[0]}N{v.family[1]}", "resolved": v.resolved,
                        "wins": v.wins, "margin_pct": round(v.margin_pct, 3),
                        "ci95": [round(x, 3) for x in v.margin_ci95]},
            "means_ms": {f"K{f[0]}N{f[1]}": round(sum(r[f] for r in races) / len(races), 4) for f in legal},
            "start_window_samples": sw, "clock_samples": n, "sweep_s": round(sweep_s, 3),
            "per_row_us": per_row,
        }
        g = rec["geoms"][geom]
        print(f"trial {trial} warm={bool(a.warm)} {geom}: {g['verdict']} sw={sw}/{n} "
              f"means={g['means_ms']}", flush=True)
        for fam, rr in per_row.items():
            print(f"    {fam}: {rr}", flush=True)
    out.append(rec)
pathlib.Path(a.out).write_text(json.dumps(out, indent=1, default=str))
print("wrote", a.out)
