#!/usr/bin/env python3
"""LikeLink Radar: the reviewer's kit. Standard library only (Python 3.8+), nothing to install.

    python3 audit.py                                   # reads https://likelink2.vercel.app/audit.json
    python3 audit.py https://likelink2.vercel.app/audit.json
    python3 audit.py audit.json                        # a downloaded copy

It recomputes, from the radar's published records and by the bars written in advance:
  1. the day's seal: SHA-256 of the root text equals the root, and the Ed25519 signature of
     "likelink2-radar|root|v1|<day>|<root>" verifies with the radar's pinned public key (RFC 8032);
  2. every claim's statistic (one-sided Fisher exact test, two-sided sign test, coverage, Brier skill)
     and its status: PROVEN, BELOW ITS BAR, IN TEST or RAW.
A status this script computes that differs from the kit's is printed as MISMATCH and the exit code is 2.
"""
import base64
import hashlib
import json
import math
import sys
import urllib.request

DEFAULT = "https://likelink2.vercel.app/audit.json"
PINNED_KEY = {"kid": "8bf2d5afd249affc", "pub": "4oMcOPLvIm7cQy+BLSTx41xox397CuEkvCloqZuI/tw="}
# The bars, as written in src/lib/radar/proven.js, src/lib/growth/radarPromise.js and docs/radar-v2/FREEZE.md.
BARS = {
    "momentum": {"minGraded": 50, "p": 0.01},
    "range": {"minGraded": 100, "tolerance": 2},
    "chance": {"minGraded": 100, "skillAbove": 0},
    "blindTestReadOn": "2026-12-29",
}

# ── Ed25519 verification, RFC 8032 section 6 (reference implementation) ──
P = 2 ** 255 - 19
Q = 2 ** 252 + 27742317777372353535851937790883648493
D = -121665 * pow(121666, P - 2, P) % P
SQRT_M1 = pow(2, (P - 1) // 4, P)


def _inv(x):
    return pow(x, P - 2, P)


def _add(a, b):
    A = (a[1] - a[0]) * (b[1] - b[0]) % P
    B = (a[1] + a[0]) * (b[1] + b[0]) % P
    C = 2 * a[3] * b[3] * D % P
    E = 2 * a[2] * b[2] % P
    e, f, g, h = B - A, E - C, E + C, B + A
    return (e * f % P, g * h % P, f * g % P, e * h % P)


def _mul(s, pt):
    out = (0, 1, 1, 0)
    while s > 0:
        if s & 1:
            out = _add(out, pt)
        pt = _add(pt, pt)
        s >>= 1
    return out


def _eq(a, b):
    return (a[0] * b[2] - b[0] * a[2]) % P == 0 and (a[1] * b[2] - b[1] * a[2]) % P == 0


def _x(y, sign):
    if y >= P:
        return None
    x2 = (y * y - 1) * _inv(D * y * y + 1) % P
    if x2 == 0:
        return None if sign else 0
    x = pow(x2, (P + 3) // 8, P)
    if (x * x - x2) % P:
        x = x * SQRT_M1 % P
    if (x * x - x2) % P:
        return None
    if (x & 1) != sign:
        x = P - x
    return x


_GY = 4 * _inv(5) % P
_GX = _x(_GY, 0)
G = (_GX, _GY, 1, _GX * _GY % P)


def _point(b):
    if len(b) != 32:
        return None
    y = int.from_bytes(b, "little")
    sign = y >> 255
    y &= (1 << 255) - 1
    x = _x(y, sign)
    return None if x is None else (x, y, 1, x * y % P)


def ed25519_verify(pub, msg, sig):
    if len(pub) != 32 or len(sig) != 64:
        return False
    A = _point(pub)
    R = _point(sig[:32])
    if A is None or R is None:
        return False
    s = int.from_bytes(sig[32:], "little")
    if s >= Q:
        return False
    h = int.from_bytes(hashlib.sha512(sig[:32] + pub + msg).digest(), "little") % Q
    return _eq(_mul(s, G), _add(R, _mul(h, A)))


# ── statistics ──
def fisher_greater(a, n1, b, n2):
    """One-sided Fisher exact test: P(X >= a), X hypergeometric, under no difference between the groups."""
    k, N = a + b, n1 + n2
    total = math.comb(N, k)
    return min(1.0, sum(math.comb(n1, x) * math.comb(n2, k - x) for x in range(a, min(k, n1) + 1)) / total)


def sign_test(wins, losses):
    n = wins + losses
    if n == 0:
        return None
    return min(1.0, 2 * sum(math.comb(n, i) for i in range(min(wins, losses) + 1)) / 2 ** n)


def rate(hits, of):
    return None if not of else round(1000 * hits / of) / 10


def recompute(c):
    """(status, detail) from the claim's own counts and the bars above."""
    d = c.get("data") or {}
    kind = c.get("kind")
    if kind == "momentum":
        r, x = d["rank"], d["random"]
        if not (r["of"] or 0) >= BARS["momentum"]["minGraded"] or not (x["of"] or 0) >= BARS["momentum"]["minGraded"]:
            return "IN_TEST", "fewer than %d graded a side" % BARS["momentum"]["minGraded"]
        p = fisher_greater(r["hits"], r["of"], x["hits"], x["of"])
        better = rate(r["hits"], r["of"]) > rate(x["hits"], x["of"])
        return ("PROVEN" if p <= BARS["momentum"]["p"] and better else "NOT_MET"), "%d/%d vs %d/%d, Fisher one-sided p = %.3g" % (r["hits"], r["of"], x["hits"], x["of"], p)
    if kind == "pick":
        m = d["mornings"]
        p = sign_test(m["wins"], m["losses"])
        return "IN_TEST", "mornings %d won, %d lost, %d tied, sign test p = %s; read once on %s" % (m["wins"], m["losses"], m["ties"], "n/a" if p is None else "%.3g" % p, BARS["blindTestReadOn"])
    if kind == "range":
        n, held, level = d.get("n"), d.get("held"), d.get("level")
        if not n or n < BARS["range"]["minGraded"]:
            return "IN_TEST", "fewer than %d graded" % BARS["range"]["minGraded"]
        rt = rate(held, n)
        ok = rt >= level - BARS["range"]["tolerance"]
        return ("PROVEN" if ok else "NOT_MET"), "held %d of %d = %.1f%% (bar %d%%)" % (held, n, rt, level - BARS["range"]["tolerance"])
    if kind == "chance":
        n, skill, how = d.get("n"), d.get("skill"), "as published"
        brier, base = d.get("brier"), d.get("baseRate")
        if brier is not None and base is not None and 0 < base < 100:
            b = base / 100
            mine = round((1 - brier / (b * (1 - b))) * 1000) / 10
            if skill is None or d.get("skillFrom") != "published":
                skill, how = mine, "computed here from Brier %.3f and base rate %.1f%%" % (brier, base)
        if not n or n < BARS["chance"]["minGraded"] or skill is None:
            return "IN_TEST", "fewer than %d graded" % BARS["chance"]["minGraded"]
        likely = d.get("likelyCalls") or {}
        tail = ", said >= 50%%: %d of %d happened" % (likely.get("hits", 0), likely.get("n", 0)) if likely.get("n") else ""
        return ("PROVEN" if skill > BARS["chance"]["skillAbove"] else "NOT_MET"), "%d graded, Brier skill %.1f%% %s%s" % (n, skill, how, tail)
    return "RAW", ", ".join("%s %s" % (k, v) for k, v in d.items())


def load(src):
    if src.startswith("http://") or src.startswith("https://"):
        req = urllib.request.Request(src, headers={"User-Agent": "likelink-audit/1"})
        with urllib.request.urlopen(req, timeout=30) as res:
            return json.loads(res.read().decode("utf-8"))
    with open(src, encoding="utf-8") as f:
        return json.load(f)


def check_seal(seal):
    lines = []
    if not seal:
        return ["seal: missing from this kit"], False
    ok = True
    text = seal.get("rootText")
    if isinstance(text, str):
        same = hashlib.sha256(text.encode("utf-8")).hexdigest() == seal.get("rootSha256")
        lines.append("seal %s: SHA-256 of the root text %s the root" % (seal.get("day"), "equals" if same else "DIFFERS FROM"))
        ok &= same
    sig = seal.get("signature") or {}
    if sig.get("b64"):
        key = seal.get("key") or {}
        pub = base64.b64decode(key.get("pub", ""))
        msg = ("likelink2-radar|root|v1|%s|%s" % (seal.get("day"), seal.get("rootSha256"))).encode("utf-8")
        good = ed25519_verify(pub, msg, base64.b64decode(sig["b64"]))
        pinned = key.get("pub") == PINNED_KEY["pub"] and key.get("kid") == PINNED_KEY["kid"]
        lines.append("signature: Ed25519 %s with key %s (%s)" % ("VERIFIES" if good else "FAILS", key.get("kid"), "the radar's pinned key" if pinned else "a key other than the pinned one"))
        ok &= good and pinned
    for b in seal.get("bitcoin") or []:
        lines.append("bitcoin: root of %s verified in block %s (check on any explorer)" % (b.get("day"), b.get("height")))
    return lines, ok


def main(argv):
    kit = load(argv[1] if len(argv) > 1 else DEFAULT)
    print("LikeLink Radar reviewer's kit · %s · board %s" % (kit.get("format"), kit.get("boardAt")))
    seal_lines, seal_ok = check_seal(kit.get("seal"))
    for line in seal_lines:
        print("  " + line)
    mismatch = 0
    counts = {}
    print("")
    for c in kit.get("claims") or []:
        status, detail = recompute(c)
        counts[status] = counts.get(status, 0) + 1
        flag = "" if status == c.get("status") else "   MISMATCH (kit says %s)" % c.get("status")
        mismatch += 1 if flag else 0
        print("%-9s %-22s %s%s" % (status, c.get("id"), detail, flag))
        print("          " + (c.get("statement") or {}).get("en", ""))
    print("")
    print("summary: " + ", ".join("%s %d" % (k, counts.get(k, 0)) for k in ("PROVEN", "IN_TEST", "NOT_MET", "RAW")))
    if not seal_ok:
        print("seal: CHECK FAILED")
    return 2 if mismatch or not seal_ok else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
