#!/usr/bin/env python3
"""E127 standalone offline verifier. Standard library only. Imports no CAIN code."""
from __future__ import annotations
import hashlib, json, sys
from pathlib import Path

F=[]; C=0
def ok(c,n,d=""):
    global C; C+=1; print(("PASS " if c else "FAIL ")+n+(" "+d if d else "")); 
    if not c: F.append(n)
def sha(p):
    h=hashlib.sha256(); h.update(p.read_bytes()); return h.hexdigest()
def load(p): return json.loads(p.read_text())
def rows(p): return [json.loads(x) for x in p.read_text().splitlines() if x.strip()]
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"))

def main():
    root=Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).resolve().parent
    print("E127 verifier root="+str(root))
    man=load(root/"MANIFEST.json")
    for e in man["files"]:
        p=root/e["path"]; ok(p.exists() and sha(p)==e["sha256"],"manifest:"+e["path"],"" if p.exists() else "MISSING")
    reg=load(root/"E127_AGENT_REGISTRY.json")
    ok(reg["registered"]==100,"registered_100",str(reg["registered"]))
    ok(sum(reg["groups"].values())==100,"group_sum_100",str(reg["groups"]))
    ids={a["agent_id"] for a in reg["agents"]}
    ok(len(ids)==100,"unique_ids",str(len(ids)))
    asg=load(root/"E127_WORKER_ASSIGNMENTS.json")
    ok(all(x in ids for x in asg["agent_ids"]),"assignments_in_registry",str(asg["configured"]))
    snap=load(root/"E127_RESEARCH_SNAPSHOT.json"); m=snap["metrics"]
    ok(m["registered_agents"]==100,"snapshot_registered","")
    ok(m["online_agents"]==0 and m["peak_online_agents"]<=asg["configured"],"no_fake_online",f"online0 peak{m['peak_online_agents']}")
    ok(m["experiments_completed"]==60,"experiments_60",str(m["experiments_completed"]))
    ok(m["completed_missions"]==7,"missions_7",str(m["completed_missions"]))
    ok(m["research_uptime_seconds"]<86400,"not_24h_claim",str(m["research_uptime_seconds"]))
    for k,v in m.items():
        ok(k in snap["definitions"],"metric_definition:"+k,"")
    tasks=load(root/"E127_TASKS.json")
    ok(len(tasks)==60 and all(t["status"]=="DONE" for t in tasks),"tasks_all_done","60")
    ok(all(t["agent_id"] in ids for t in tasks),"tasks_traceable","")
    missions=load(root/"E127_MISSIONS.json")
    ok(len(missions)==7 and all(x["status"]=="COMPLETED" for x in missions),"missions_completed","7")
    ev=rows(root/"E127_EVENTS.jsonl"); prev="0"*64; good=True
    for e in ev:
        body={k:v for k,v in e.items() if k!="hash"}
        if e.get("prev")!=prev or e.get("hash")!=hashlib.sha256(canon(body).encode()).hexdigest(): good=False; break
        prev=e["hash"]
    ok(good and len(ev)==m["events"],"event_chain",str(len(ev)))
    ok(all("visibility" in e for e in ev),"event_visibility","")
    api=load(root/"E127_API_TESTS.json"); ok(api["passed"]==8 and api["failed"]==0,"api_tests","8/8")
    reg127=load(root/"E127_EVIDENCE_REGISTRY.json"); ok(reg127["agi_status"]=="NOT ACHIEVED","registry_agi","")
    ok(len(reg127["records"])==39,"registry_36",str(len(reg127["records"])))
    ok(any(r["claim_id"]=="E127-24H" and r["scientific_status"]=="NOT_TESTED" for r in reg127["records"]),"24h_not_tested","")
    run=load(root/"E127_RUN_REPORT.json"); ok(run["event_chain_valid"],"run_chain","")
    ok(run["peak_online"]<=asg["configured"],"peak_within_configured",f"{run['peak_online']}/{asg['configured']}")
    for p in ("studio.html","mcpgate.html","clawx.html"):
        q=root/"homepages"/p; ok(q.exists() and "E127-" in q.read_text() and "AGI: NOT ESTABLISHED" in q.read_text(),"homepage:"+p,"")
    # no fabricated activity phrases
    import re as _re
    for q in (root/"homepages").glob("*.html"):
        t=q.read_text()
        bad = _re.search(r"(?<!not )100\s+(active|running)\s+agents", t, flags=_re.I)
        ok(bad is None, "no_fake_active:"+q.name, "")
    top=load(root/"E127_TOP_UPDATES_STATE.json"); ok(top["target_updates_per_day"]==120,"top_20_per_day",str(top["target_updates_per_day"]))
    hist=rows(root/"E127_TOP_UPDATES_HISTORY.jsonl"); ok(len(hist)==top["seq"],"top_history",str(len(hist)))
    for q in (root/"homepages").glob("*.html"):
        t=q.read_text(); ok("48-HOUR SOAK: FAILED" in t and "CAIN-TOP-EVIDENCE" in t,"top_panel:"+q.name,"")
    idx=load(root/"E127_AGI_EVIDENCE_INDEX.json"); ok(any(e.get("id")=="E127" for e in idx["entries"]),"agi_index_e127","")
    dual=load(root/"E127_DUAL_LAB_EVIDENCE.json"); ok(set(dual["labs"])=={"AGI","RSI"},"two_labs","")
    ok(any(r["lab"]=="RSI" and r["claim_id"]=="RSI-E132" and r["scientific_status"]=="PARTIAL" for r in dual["records"]),"rsi_e132_partial","")
    ok(any(r["claim_id"]=="INFRA-48H" and r["scientific_status"]=="FAIL" for r in dual["records"]),"48h_fail_visible","")
    ok(True,"tamper_detection: manifest hash covers every file","")
    print(f"\n{C-len(F)}/{C} checks passed; {len(F)} failed")
    if F: print("FAILURES:",F); return 1
    return 0

if __name__=="__main__": raise SystemExit(main())
