"""Tested example: recompute the parent (seed) and the para-iodo salt from the packaged inputs and compare with the
reported values. Uses only code/ (t1_gamma2_core.py, t1_recompute.py) — no El Agente installation.

    python tests/test_parent_iodine.py            # Gamma check (seconds) + dense check (a few minutes per salt)
    python tests/test_parent_iodine.py --gamma    # Gamma check only

Expected values:
- Gamma: the validator's signed T1 (judge_t1_loop receipts rcpt-72d672d9683b for the seed, rcpt-f0670a4fa30c for
  para-I; copies in inputs/<salt>/reported/). Tolerance 1e-6 relative (same code, same inputs).
- Dense: the paper's matched dense-sampling T1 (paper_package data/t1_vs_sigma.csv, rounded to 4 decimals in µs).
  Tolerance 0.0005 µs absolute.
"""
import json
import sys
import time
from pathlib import Path

HERE = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(HERE / "code"))
from t1_recompute import t1_dense, t1_gamma  # noqa: E402

GAMMA_EXPECTED = {  # µs, from the validator receipts
    "SEED": {"5": 2.0035510157789222, "10": 1.757688794307013, "20": 1.7993982617606458},
    "R5_pI": {"5": 2.930809454844348, "10": 1.7394091752430177, "20": 1.4550388039753738},
}
DENSE_EXPECTED = {  # µs, paper data/t1_vs_sigma.csv (sampling = dense)
    "SEED": {"grid": [2, 2, 2], "n_modes": 1552, "T1_us": {"3": 2.4323, "5": 1.9921, "7": 1.7979}},
    "R5_pI": {"grid": [3, 2, 2], "n_modes": 1237, "T1_us": {"3": 3.7218, "5": 2.8752, "7": 2.1915}},
}


def load(salt, name):
    return json.loads((HERE / "inputs" / salt / name).read_text())


def check_gamma():
    for salt, exp in GAMMA_EXPECTED.items():
        got = t1_gamma(load(salt, "couplings_judged.json"), [5, 10, 20])
        for s, v in exp.items():
            rel = abs(got[s] / v - 1)
            print(f"gamma  {salt:6s} sigma {s:>2s}: {got[s]:.6f} us  (validator {v:.6f})  rel diff {rel:.1e}")
            assert rel < 1e-6, (salt, s, got[s], v)
    r = {s: GAMMA_EXPECTED["R5_pI"][s] / GAMMA_EXPECTED["SEED"][s] for s in ("5", "10", "20")}
    print("gamma  ratio para-I / seed:", {s: round(x, 4) for s, x in r.items()})


def check_dense():
    res = {}
    for salt, exp in DENSE_EXPECTED.items():
        t0 = time.time()
        files = json.loads((HERE / "inputs" / salt / "inputs.json").read_text())["files"]
        out = t1_dense(load(salt, files["couplings_dense"]["file"]), load(salt, files["displacement_manifest_dense"]["file"]),
                       str(HERE / "inputs" / salt / "phonopy_params.yaml"), [3, 5, 7])
        assert out["grid"] == exp["grid"] and out["n_modes"] == exp["n_modes"], (salt, out["grid"], out["n_modes"])
        for s, v in exp["T1_us"].items():
            print(f"dense  {salt:6s} sigma {s}: {out['T1_us'][s]:.4f} us  (paper {v:.4f})  grid {out['grid']}, {out['n_modes']} modes  [{time.time()-t0:.0f} s]")
            assert abs(out["T1_us"][s] - v) < 5e-4, (salt, s, out["T1_us"][s], v)
        res[salt] = out["T1_us"]
    ratio = {s: res["R5_pI"][s] / res["SEED"][s] for s in ("3", "5", "7")}
    print("dense  ratio para-I / seed:", {s: round(x, 3) for s, x in ratio.items()})
    assert all(x >= 1.2 for x in ratio.values()), ratio  # the paper's claim at sigma 3-7


if __name__ == "__main__":
    assert "Hypothesis_generation" not in sys.modules
    check_gamma()
    if "--gamma" not in sys.argv:
        check_dense()
    assert not any(m.startswith(("Hypothesis_generation", "ElAgente")) for m in sys.modules), "El Agente was imported"
    print("ALL CHECKS PASSED")
