"""Day 5 MHIS run: Gate M0 verification + n=2^18 (batch_size=128, burn_in=1024, seed=6000+t) on camel & english,
plus secondary camel temp=1.0 diagnostic (n=2^16, batch_size=128, burn_in=512, seed=7000+t).
Usage:
  python3 run_day5_mhis.py gate THREADS
  python3 run_day5_mhis.py run DIST WORKER_ID NUM_WORKERS THREADS [MODE]
    where MODE is 'main_2p18' (default) or 'camel_temp1'
Frozen plan: PLAN.md (tracker #71 / #77). Written by Gemini 4 Carbon (High), 2026-11-23.
"""
import json, os, resource, sys, time
import torch as th

OLD = os.environ.get("OLD", "/old")
WORK = os.environ.get("WORK", "/work")
sys.path.insert(0, f"{OLD}/code")
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.environ["JOB"] = OLD

import arcenv
from mhis_fast import mhis_fast

cmd = sys.argv[1]

if cmd == "gate":
    nth = int(sys.argv[2])
    th.set_num_threads(nth)
    methods, mu = arcenv.import_lpe()
    model = arcenv.load_model()
    from lpe.utils import distribution_registry

    orig_hex = distribution_registry["hex"](model.tokenizer).input_dists(n_reps=mu.N_REPS_DICT["hex"])
    temp_hex = mu.RECOMMENDED_TEMPS["gelu-1l"]["MHIS"]["hex"]

    # Check 1: Non-zero short run vs unedited lpe.methods.MHIS
    gt_hex = th.load(f"{OLD}/gt/gelu-1l-hex.pt", map_location="cpu", weights_only=True).double() / 2**32
    t_short = 67
    th.manual_seed(4242)
    e_orig = float(methods.MHIS(model, orig_hex, t_short, temp=temp_hex, n_samples=256, burn_in=4, batch_size=32))
    th.manual_seed(4242)
    e_fast, _, hits_s, _, _ = mhis_fast(model, orig_hex, t_short, temp=temp_hex, n_samples=256, burn_in=4, batch_size=32)
    rel_short = abs(e_orig - e_fast) / max(abs(e_orig), 1e-30)

    # Check 2: Full n=2^16, batch_size=32, burn_in=1024, seed=5000+420 vs day23/out/hex/mhis.json["420"]
    ref_420 = float(json.load(open(f"{OLD}/out/hex/mhis.json"))["420"]["est"])
    t0 = time.time()
    th.manual_seed(5000 + 420)
    e_420, acc_420, hits_420, _, _ = mhis_fast(model, orig_hex, 420, temp=temp_hex, n_samples=2**16, burn_in=1024, batch_size=32)
    rel_420 = abs(e_420 - ref_420) / max(abs(ref_420), 1e-30)

    gate = {
        "short_token_67": {"orig": e_orig, "fast": e_fast, "hits": hits_s, "rel_diff": rel_short, "pass": rel_short <= 1e-5},
        "full_hex_420": {"ref_day23": ref_420, "fast": e_420, "hits": hits_420, "acc_rate": acc_420, "rel_diff": rel_420, "sec": time.time() - t0, "pass": rel_420 <= 1e-4},
    }
    gate["pass"] = gate["short_token_67"]["pass"] and gate["full_hex_420"]["pass"]
    os.makedirs(f"{WORK}/out", exist_ok=True)
    json.dump(gate, open(f"{WORK}/out/gate_m0.json", "w"), indent=1)
    print("GATE M0:", json.dumps(gate), flush=True)
    if not gate["pass"]:
        raise RuntimeError(f"Gate M0 failed: {gate}")
    sys.exit(0)

assert cmd == "run"
dist = sys.argv[2]
wid = int(sys.argv[3])
nw = int(sys.argv[4])
nth = int(sys.argv[5])
mode = sys.argv[6] if len(sys.argv) > 6 else "main_2p18"

th.set_num_threads(nth)
_, mu = arcenv.import_lpe()
model = arcenv.load_model()
from lpe.utils import distribution_registry
orig = distribution_registry[dist](model.tokenizer).input_dists(n_reps=mu.N_REPS_DICT[dist])

tok = json.load(open(f"{OLD}/out/tokens.json"))[dist]
mhis_tokens = tok["mhis_tokens"]
my_tokens = [t for idx, t in enumerate(mhis_tokens) if idx % nw == wid]

if mode == "main_2p18":
    temp = mu.RECOMMENDED_TEMPS["gelu-1l"]["MHIS"][dist]
    n_samples = 2**18 if dist in ("camel", "english") else 2**16
    batch_size = 128
    burn_in = 1024
    seed_base = 6000
    sub = "mhis_2p18" if dist in ("camel", "english") else "mhis_hex_recheck"
elif mode == "camel_temp1":
    assert dist == "camel"
    temp = 1.0
    n_samples = 2**16
    batch_size = 128
    burn_in = 512
    seed_base = 7000
    sub = "mhis_camel_temp1"
else:
    raise ValueError(f"unknown mode {mode}")

OUT = f"{WORK}/out/{dist}/{sub}"
os.makedirs(OUT, exist_ok=True)
print(f"[{dist}:{mode}:w{wid}/{nw}] tokens={my_tokens} temp={temp} n={n_samples} B={batch_size} burn={burn_in}", flush=True)

for t in my_tokens:
    out_p = f"{OUT}/tok_{t}.json"
    if os.path.exists(out_p):
        print(f"[{dist}:{mode}:w{wid}] token {t} already done, skipping", flush=True)
        continue
    p_true = float(tok["p"][tok["tokens"].index(t)])
    th.manual_seed(seed_base + t)
    t0 = time.time()
    try:
        est, acc, hits, num_mean, den_mean = mhis_fast(
            model, orig, t, temp=temp, n_samples=n_samples, burn_in=burn_in, batch_size=batch_size
        )
        err = None
    except Exception as ex:
        est, acc, hits, num_mean, den_mean, err = 0.0, 0.0, 0, 0.0, 0.0, repr(ex)[:200]
    rec = {
        "token": int(t),
        "p": p_true,
        "est": float(est),
        "hits": int(hits),
        "accept_rate": float(acc),
        "num_mean": float(num_mean),
        "den_mean": float(den_mean),
        "temp": float(temp),
        "n_samples": int(n_samples),
        "batch_size": int(batch_size),
        "burn_in": int(burn_in),
        "seed": int(seed_base + t),
        "sec": time.time() - t0,
        "rss_mb": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.0,
        "err": err,
    }
    tmp = out_p + ".tmp"
    json.dump(rec, open(tmp, "w"), indent=1)
    os.replace(tmp, out_p)
    print(time.strftime("%H:%M:%S"), f"[{dist}:{mode}:w{wid}] token {t} est={est:.4e} p={p_true:.4e} hits={hits} sec={rec['sec']:.1f}s", flush=True)

print(time.strftime("%H:%M:%S"), f"[{dist}:{mode}:w{wid}] WORKER DONE", flush=True)
