#!/usr/bin/env python3
"""Standalone E175 verifier: re-runs hidden software tests and independent math checks. No CAIN imports."""
from __future__ import annotations
import hashlib,json,math,subprocess,sys,tempfile
from pathlib import Path
STATUS="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":")).encode()
def sha(s): return hashlib.sha256(s.encode()).hexdigest()
def merkle(paths):
    leaves=sorted(hashlib.sha256(p.read_bytes()).hexdigest() for p in paths)
    if not leaves: return hashlib.sha256(b"").hexdigest()
    while len(leaves)>1:
        if len(leaves)%2: leaves.append(leaves[-1])
        leaves=[hashlib.sha256((leaves[i]+leaves[i+1]).encode()).hexdigest() for i in range(0,len(leaves),2)]
    return leaves[0]
def run_hidden(code, hidden):
    d=Path(tempfile.mkdtemp(prefix="e175v-")); (d/"solution.py").write_text(code)
    (d/"test.py").write_text("import sys, os\nsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\nfrom solution import *\n"+hidden+"\nprint('HIDDEN_OK')\n")
    try:
        r=subprocess.run([sys.executable,"-I","test.py"],cwd=d,capture_output=True,text=True,timeout=10)
        return r.returncode==0 and "HIDDEN_OK" in r.stdout
    except Exception:
        return False
def math_checks(key):
    import sympy as sp, mpmath as mp
    out={}
    G=[(0,1),(1,2),(2,3),(3,0),(0,4),(1,5),(2,6),(3,7),(4,5),(5,6),(6,7),(7,4),(0,2),(4,6)]
    L=sp.zeros(8)
    for u,v in G: L[u,u]+=1; L[v,v]+=1; L[u,v]-=1; L[v,u]-=1
    out["M01"]=int(L[1:,1:].det())==int(key["M01"])
    out["M02"]=next(x for x in range(5005) if all(x%m==r for m,r in zip([5,7,11,13],[2,3,5,7])))==int(key["M02"])
    out["M03"]=int(sp.partition(120))==int(key["M03"])
    ex=sp.sympify(key["M04"]); val=mp.quad(lambda t:t**3*(1-t)**5/(1+t),[0,1])
    out["M04"]=abs(val-mp.mpf(str(ex.evalf(60))))<mp.mpf("1e-30")
    ex5=sp.sympify(key["M05"]); v5=mp.nsum(lambda k:1/(k**2*(k+1)**2),[1,mp.inf])
    out["M05"]=abs(v5-mp.mpf(str(ex5.evalf(60))))<mp.mpf("1e-30")
    out["M06"]=int(sp.Matrix([[5 if i==j else 1 for j in range(12)] for i in range(12)]).det())==int(key["M06"])
    a,b=0,1
    for _ in range(10000): a,b=b,(a+b)%1_000_000_007
    out["M07"]=a==int(key["M07"])
    out["M08"]=int(sp.subfactorial(50))%1_000_000_007==int(key["M08"])
    out["M09"]=int(sp.n_order(2,1_000_000_007))==int(key["M09"])
    out["M10"]=int(sp.primepi(2_000_000))==int(key["M10"])
    return out
def main():
    B=Path(sys.argv[1] if len(sys.argv)>1 else "."); checks=[]
    def ck(n,ok,d=""): checks.append({"check":n,"ok":bool(ok),"detail":str(d)[:300]})
    man=json.loads((B/"E175_MANIFEST.json").read_text()); ck("status line",man.get("status")==STATUS)
    body={k:v for k,v in man.items() if k!="signature"}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]),canon(body)); ck("signature",True)
    except Exception as e: ck("signature",False,e)
    f=man.get("files",{}); ck("files exist",all((B/k).exists() for k in f)); bad=[k for k,h in f.items() if (B/k).exists() and hashlib.sha256((B/k).read_bytes()).hexdigest()!=h]; ck("hashes",not bad,bad[:3])
    ck("merkle",merkle(sorted(B/k for k in f if (B/k).exists()))==man.get("merkle_root"))
    present={str(x.relative_to(B)) for x in B.rglob("*") if x.is_file()}
    unlisted=sorted(present-set(f)-{"E175_MANIFEST.json","E175_VERIFICATION_RESULTS.json","PUBLICATION.json"})
    ck("no unlisted file",not unlisted,unlisted[:5])
    pre=B/"E175_PREREGISTRATION.json"; ck("prereg",pre.exists() and hashlib.sha256(pre.read_bytes()).hexdigest()==man.get("preregistration_sha256"))
    key=json.loads((B/"E175_ANSWER_KEY.json").read_text()); soft=json.loads((B/"E175_SOFTWARE_REPORT.json").read_text())
    ck("software 10/10",soft["solved"]==soft["n"]==10,soft["solved"])
    for p in soft["problems"]:
        ck(f"{p['id']} hidden transcript",p["solved"] is True and p["hidden_output"].startswith("HIDDEN_OK"))
        ck(f"{p['id']} prompt public-only",sha(p["prompt"])==p["prompt_sha256"] and key["software"][p["id"]]["hidden"] not in p["prompt"])
        ck(f"{p['id']} hidden hash",sha(key["software"][p["id"]]["hidden"])==p["hidden_tests_sha256"])
        ck(f"{p['id']} code commitment",key["software"][p["id"]].get("code_sha256")==p["code_sha256"] and key["software"][p["id"]].get("solution_path")=="WITHHELD_PRIVATE_VAULT")
        ck(f"{p['id']} no model source in bundle",not (B/"software").exists())
    mc=math_checks(key["math"]); ck("math 10/10",all(mc.values()),mc)
    ck("math report 10/10",json.loads((B/"E175_MATH_REPORT.json").read_text())["solved"]==10)
    ck("no AGI/RSI claim","NOT ESTABLISHED" in json.loads((B/"E175_EXPERIMENT_SUMMARY.json").read_text()).get("status",""))
    pub=B/"PUBLICATION.json"
    if pub.exists():
        pj=json.loads(pub.read_text()); ck("publication merkle",pj.get("merkle_root")==man.get("merkle_root")); ck("four surfaces",len(pj.get("surfaces",{}))==4)
    else: ck("pre-publication",True)
    ok=all(c["ok"] for c in checks); print(json.dumps({"checks":len(checks),"passed":sum(c["ok"] for c in checks),"ok":ok}))
    for c in checks:
        if not c["ok"]: print("FAIL",c["check"],c["detail"])
    return 0 if ok else 1
if __name__=="__main__": sys.exit(main())
