import os, json, datetime
from .common import sha256_file

def gate_nz(dataset_dir: str) -> dict:
    path = os.path.join(dataset_dir,"nz_metrics.json")
    with open(path,"r",encoding="utf-8") as f:
        m = json.load(f)
    smin_L = float(m["smin_L"])
    smin_U = float(m["smin_U"])
    rho_max = float(m["rho_max"])
    eps_m = float(m.get("eps_m", 0.0))
    pass_rule = (rho_max <= 1.0 - eps_m)

    return {
        "row": 22,
        "gate": "neutral_zone_sandwich",
        "context": "LIVE",
        "tier": "Diagnostic",
        "timestamp_utc": datetime.datetime.utcnow().isoformat(timespec="seconds")+"Z",
        "metrics": {"smin_L": smin_L, "smin_U": smin_U, "rho_max": rho_max, "eps_m": eps_m},
        "rule": "rho_max <= 1 - eps_m",
        "verdict": "PASS" if pass_rule else "FAIL",
        "blocking": False,
        "inputs": {"hashes": {"nz_metrics.json": sha256_file(path)}}
    }

if __name__ == "__main__":
    here=os.path.dirname(__file__)
    dataset_dir=os.path.abspath(os.path.join(here,"..","datasets"))
    out_dir=os.path.abspath(os.path.join(here,"..","results","row22_nz"))
    os.makedirs(out_dir, exist_ok=True)
    res=gate_nz(dataset_dir)
    with open(os.path.join(out_dir,"result.json"),"w",encoding="utf-8") as f:
        json.dump(res,f,indent=2,sort_keys=True)
    print(json.dumps(res["metrics"], indent=2))
