# -*- coding: utf-8 -*-
"""
SOL AUDIT 2 — audit what is actually PUBLISHED on agnt.gg (not local files).
Downloads the whitepaper + artifacts over HTTPS, verifies hashes against the
served SHA256SUMS, and independently re-verifies the two headline objects:
the 22-dim degree-3 counterexample and the Dixmier certificate content.
"""
import urllib.request, hashlib, json, ssl, time, random
import sympy as sp

t0 = time.time()
random.seed(31337)
BASE = "https://agnt.gg/whitepapers/"
ART = BASE + "post-jc-artifacts/"
V = {}
def verdict(k, ok, note=""):
    V[k] = {"pass": bool(ok), "note": note}
    print(f"[{'PASS' if ok else 'FAIL'}] {k}" + (f"  ({note})" if note else ""), flush=True)

ctx = ssl.create_default_context()
def get(url):
    with urllib.request.urlopen(url, context=ctx, timeout=60) as r:
        return r.read()

sums = get(ART + "SHA256SUMS.txt").decode().strip().splitlines()
sums = dict(reversed(l.split(None, 1)) for l in sums if l.strip())
verdict("B1 SHA256SUMS served and parseable", len(sums) >= 14, f"{len(sums)} entries")

# verify every listed artifact hash against served bytes
allok, checked = True, 0
for fn, h in sums.items():
    url = (BASE + fn[3:]) if fn.startswith('../') else (ART + fn)
    hh = hashlib.sha256(get(url)).hexdigest()
    checked += 1
    if hh != h:
        allok = False
        print(f"   MISMATCH: {fn}", flush=True)
verdict("B2 every served artifact matches its published SHA-256", allok, f"{checked} files")

# independently re-verify the degree-3 counterexample FROM THE SERVED JSON
art = json.loads(get(ART + "degree3_counterexample.json"))
Vs = [sp.Symbol(v) for v in art["variables"]]
Fs = [sp.sympify(c) for c in art["components"]]
N = len(Vs)
verdict("B3a dim 22, 22 components", N == 22 == len(Fs))
ok_deg = True
for k in range(N):
    h = sp.expand(Fs[k] - Vs[k])
    if h == 0: continue
    ds = {sum(mm) for mm in sp.Poly(h, *Vs).monoms()}
    if not ds <= {2, 3}: ok_deg = False
verdict("B3b every H_k monomial degree in {2,3}, max 3 attained",
        ok_deg and max(sp.total_degree(sp.expand(Fs[k]-Vs[k])) for k in range(N) if sp.expand(Fs[k]-Vs[k])!=0) == 3)
Jb = sp.Matrix(Fs).jacobian(Vs)
verdict("B3c J(0) == I", Jb.subs({v: 0 for v in Vs}) == sp.eye(N))
okdet = True
for _ in range(3):
    su = {v: sp.Rational(random.randint(-8, 8), random.randint(1, 5)) for v in Vs}
    if Jb.subs(su).det() != 1: okdet = False
verdict("B3d det J == 1 at 3 fresh exact random points", okdet)
pp = [[sp.sympify(c) for c in p] for p in art["collision_points"]]
im = [tuple(sp.expand(f.subs(dict(zip(Vs, p)))) for f in Fs) for p in pp]
verdict("B3e collision: 3 distinct points, equal images",
        len({tuple(p) for p in pp}) == 3 and im[0] == im[1] == im[2])

# Dixmier: re-verify the SERVED witness matrix (not rebuilt — audit what's public)
cert = json.loads(get(ART + "dixmier_certificate.json"))
x, y, z = sp.symbols('x y z')
Fb = [sp.sympify(sf) for sf in cert["base_map_F"]]
Jc = sp.Matrix(Fb).jacobian([x, y, z])
Gs = sp.Matrix([[sp.sympify(cert["witness_G_rows_are_phi_d_coeffs"][i][j]) for j in range(3)] for i in range(3)])
verdict("B4a served det J == -2", sp.expand(Jc.det()) == -2)
verdict("B4b served G satisfies G*J^T == I", all(e == 0 for e in (Gs*Jc.T - sp.eye(3)).applyfunc(sp.expand)))
okc = True
X3 = [x, y, z]
for i in range(3):
    for j in range(i+1, 3):
        for l in range(3):
            if sp.expand(sum(Gs[i,k]*sp.diff(Gs[j,l], X3[k]) - Gs[j,k]*sp.diff(Gs[i,l], X3[k]) for k in range(3))) != 0:
                okc = False
verdict("B4c served G: all 27 commutation identities hold", okc)

json.dump(V, open('post-jc-program/audit-sol/audit2_verdicts.json', 'w'), indent=2)
np_ = sum(1 for v in V.values() if v['pass'])
print(f"\nAUDIT 2: {np_}/{len(V)} PASS  ({round(time.time()-t0,1)}s)", flush=True)
