"""CAIN-A75-054 offline verifier (rules embedded verbatim). CAIN-A75-054 deployment-trace evaluation rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

A team turned production agent traces into a frozen behaviour test suite and re-ran it after changes. The package claims the
suite is consented, redacted, tenant-separated, frozen and honestly scored. The review recomputes it:

  consent    every test names a source trace whose consent and tenant approval were granted by named humans before the
             suite was frozen, and whose tenant is on the suite's approved list; a test keeps its trace's tenant
  redaction  no test input still contains a secret or personal datum: e-mail address, Luhn-valid card number, API key
             (sk-/ghp_/xox*), AWS access key id, private-key block or grouped phone number of 8-15 digits (scanned here, not taken on trust)
  freeze     the suite hash equals SHA-256 of the canonical test list recomputed here; it was frozen by someone other than
             the agent under test, and no edit is recorded after the freeze
  runs       every run names the frozen hash, runs after the freeze, and reports exactly one result for every test and
             nothing else; every result names the trace it came from (via its test)
  delta      each run's stated newly-failing and newly-passing sets equal the difference from the previous run recomputed here
  claims     every boolean the package asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND.
It reviews the suite and run record; it does not re-execute the agent or judge whether the tests are good tests.
"""
from __future__ import annotations

import hashlib
import json
import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/]{1,120}$")
_HEX = re.compile(r"^[0-9a-f]{64}$")
PATTERNS = {
    "email": re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}"),
    "api_key": re.compile(r"\b(sk-[A-Za-z0-9_\-]{16,}|ghp_[A-Za-z0-9]{20,}|xox[abpr]-[A-Za-z0-9\-]{10,})"),
    "aws_key_id": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
    "private_key": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
}
_PHONE = re.compile(r"(?<![\w+.])(\+\d{1,3}[ \-]?)?(\(?\d{2,4}\)?[ \-]){1,3}\d{3,4}(?![\w.])")
_CARD = re.compile(r"(?<!\d)(?:\d[ \-]?){13,19}(?!\d)")


class Bad(ValueError):
    pass


def _luhn(digits):
    s, alt = 0, False
    for d in reversed(digits):
        n = int(d)
        if alt:
            n *= 2
            n -= 9 if n > 9 else 0
        s += n
        alt = not alt
    return s % 10 == 0


def leaks(text):
    """Names of the secret / personal-data classes found in `text`."""
    found = sorted(k for k, p in PATTERNS.items() if p.search(text))
    if any(8 <= len(re.sub(r"\D", "", m.group(0))) <= 15 for m in _PHONE.finditer(text)):
        found.append("phone")
    for m in _CARD.finditer(text):
        d = re.sub(r"\D", "", m.group(0))
        if 13 <= len(d) <= 19 and _luhn(d):
            found.append("card_number")
            break
    return sorted(set(found))


def suite_hash(tests):
    return hashlib.sha256(json.dumps(tests, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()).hexdigest()


def _num(v, what, lo=0.0, hi=1e15):
    if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) or not (lo <= v <= hi):
        raise Bad(f"{what} must be a finite number in [{lo}, {hi}]")
    return float(v)


def _id(v, what):
    if not isinstance(v, str) or not _ID.match(v):
        raise Bad(f"{what} must be an id")
    return v


def _human(p):
    return isinstance(p, str) and p.startswith("human:") and len(p) > 6


def evaluate(record):
    checks, summary = [], {"runs": []}

    def c(cid, ok, detail=""):
        checks.append({"id": cid, "ok": bool(ok), "detail": detail})

    try:
        if not isinstance(record, dict) or record.get("schema") != "cain42.a75.tracebench.review.v1":
            raise Bad("not a cain42.a75.tracebench.review.v1 record")
        suite, agent = record.get("suite"), record.get("agent_under_test")
        if not isinstance(suite, dict) or not isinstance(agent, str):
            raise Bad("suite must be an object and agent_under_test a string")
        frozen_at = _num(suite.get("frozen_at"), "suite.frozen_at")
        approved = set(suite.get("approved_tenants") or [])
        traces = record.get("traces")
        if not isinstance(traces, list) or not traces:
            raise Bad("traces must be a non-empty list")
        T = {}
        for t in traces:
            if not isinstance(t, dict):
                raise Bad("a trace must be an object")
            tid = _id(t.get("id"), "trace.id")
            if tid in T:
                raise Bad(f"duplicate trace {tid}")
            T[tid] = t
            con = t.get("consent") if isinstance(t.get("consent"), dict) else {}
            app = t.get("tenant_approval") if isinstance(t.get("tenant_approval"), dict) else {}
            c(f"trace.{tid}.source_hash", isinstance(t.get("source_sha256"), str) and bool(_HEX.match(t["source_sha256"])),
              "source production record committed by SHA-256")
            c(f"trace.{tid}.consent", con.get("granted") is True and _human(con.get("by"))
              and _num(con.get("at"), f"{tid}.consent.at") <= frozen_at, f"consent by {con.get('by')!r} before freeze")
            c(f"trace.{tid}.tenant_approval", app.get("granted") is True and _human(app.get("by"))
              and _num(app.get("at"), f"{tid}.approval.at") <= frozen_at, f"tenant approval by {app.get('by')!r} before freeze")
            c(f"trace.{tid}.tenant_approved", t.get("tenant") in approved, f"tenant {t.get('tenant')!r} on the approved list")

        tests = suite.get("tests")
        if not isinstance(tests, list) or not tests:
            raise Bad("suite.tests must be a non-empty list")
        X = {}
        for x in tests:
            if not isinstance(x, dict):
                raise Bad("a test must be an object")
            xid = _id(x.get("id"), "test.id")
            if xid in X:
                raise Bad(f"duplicate test {xid}")
            X[xid] = x
            tr = T.get(x.get("trace_id"))
            c(f"test.{xid}.trace", tr is not None, f"source trace {x.get('trace_id')!r}")
            if tr is not None:
                c(f"test.{xid}.tenant", x.get("tenant") == tr.get("tenant"), f"tenant {x.get('tenant')!r} vs trace {tr.get('tenant')!r}")
            found = leaks(json.dumps(x.get("input"), ensure_ascii=False))
            c(f"test.{xid}.redacted", not found, f"still contains {found}" if found else "no secret or personal data found")

        h = suite_hash(tests)
        c("suite.hash", suite.get("sha256") == h, f"stated hash matches recomputed {h[:12]}")
        c("suite.frozen_by_other", _human(suite.get("frozen_by")) and suite.get("frozen_by") != agent,
          f"frozen by {suite.get('frozen_by')!r}, agent {agent!r}")
        edits = [e for e in (suite.get("edits") or []) if isinstance(e, dict)]
        late = [e for e in edits if _num(e.get("at"), "edit.at") > frozen_at]
        c("suite.no_edit_after_freeze", not late, f"{len(late)} edit(s) after the freeze")
        c("suite.agent_never_edited", not any(e.get("by") == agent for e in edits), "the agent under test never edited the suite")

        runs = record.get("runs")
        if not isinstance(runs, list) or not runs:
            raise Bad("runs must be a non-empty list")
        prev_fail = None
        for k, r in enumerate(runs):
            if not isinstance(r, dict):
                raise Bad("a run must be an object")
            rid = f"run.{k}"
            c(f"{rid}.suite_hash", r.get("suite_sha256") == h, "ran the frozen suite")
            c(f"{rid}.after_freeze", _num(r.get("at"), f"{rid}.at") >= frozen_at, "ran after the freeze")
            res = r.get("results")
            if not isinstance(res, list):
                raise Bad(f"{rid}.results must be a list")
            ids = [x.get("test_id") for x in res if isinstance(x, dict)]
            unknown = sorted({i for i in ids if i not in X}, key=str)
            dup = sorted({i for i in ids if ids.count(i) > 1}, key=str)
            missing = sorted(set(X) - set(ids))
            c(f"{rid}.coverage", not unknown and not dup and not missing,
              f"unknown {unknown}, duplicate {dup}, missing {missing}" if (unknown or dup or missing) else "every test exactly once")
            bad_out = [x.get("test_id") for x in res if isinstance(x, dict) and x.get("outcome") not in ("pass", "fail")]
            c(f"{rid}.outcomes", not bad_out, f"invalid outcome for {bad_out}" if bad_out else "pass/fail only")
            fail = {x.get("test_id") for x in res if isinstance(x, dict) and x.get("outcome") == "fail" and x.get("test_id") in X}
            if prev_fail is not None:
                d = r.get("delta") if isinstance(r.get("delta"), dict) else {}
                nf, np_ = sorted(fail - prev_fail), sorted(prev_fail - fail)
                c(f"{rid}.delta", sorted(d.get("newly_failing") or []) == nf and sorted(d.get("newly_passing") or []) == np_,
                  f"stated {d.get('newly_failing')}/{d.get('newly_passing')} vs recomputed {nf}/{np_}")
            summary["runs"].append({"agent_version": r.get("agent_version"), "failing": sorted(fail),
                                    "traces_failing": sorted({X[i].get("trace_id") for i in fail})})
            prev_fail = fail

        claims = record.get("claims") if isinstance(record.get("claims"), dict) else {}

        def all_ok(pred):
            return all(x["ok"] for x in checks if pred(x["id"]))

        computed = {"consented_and_approved": all_ok(lambda i: i.startswith("trace.") or i.endswith((".trace", ".tenant"))),
                    "redacted": all_ok(lambda i: i.endswith(".redacted")),
                    "frozen": all_ok(lambda i: i.startswith("suite.")),
                    "runs_complete": all_ok(lambda i: i.startswith("run.") and not i.endswith(".delta")),
                    "delta_recorded": all_ok(lambda i: i.endswith(".delta")) and len(runs) > 1}
        for k in sorted(claims):
            c(f"claims.{k}", k in computed and claims[k] == computed[k], f"claimed {claims[k]!r}, computed {computed.get(k)!r}")
        summary["computed"] = computed
        summary["suite_sha256"] = h
    except Bad as e:
        checks.append({"id": "input.well_formed", "ok": False, "detail": str(e)})
        return "UNSOUND", checks, summary
    except Exception as e:  # noqa: BLE001
        checks.append({"id": "input.error", "ok": False, "detail": f"{type(e).__name__}: {e}"[:200]})
        return "UNSOUND", checks, summary
    return ("SOUND" if all(x["ok"] for x in checks) else "UNSOUND"), checks, summary


# ---------------------------------------------------------------------------- offline verifier (no CAIN imports)
# Every name below is prefixed _kit_verifier_ / _b64 / _hl / _json / _sys so it cannot shadow a name in the rules above.
import base64 as _b64, hashlib as _hl, json as _json, sys as _sys
_KIT_VERIFIER_GENESIS = _hl.sha256(b"cain42.a75.tracebench.genesis").hexdigest()


def _kit_verifier_canon(o):
    return _json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode()


def _kit_verifier_sha(o):
    return _hl.sha256(_kit_verifier_canon(o)).hexdigest()


def _kit_verifier_main(argv):
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    if len(argv) < 2:
        print("usage: verify_offline.py run.json --pinned-key BASE64"); return 2
    run = _json.load(open(argv[1]))
    pin = argv[argv.index("--pinned-key") + 1] if "--pinned-key" in argv else None
    problems, prev, recs = [], _KIT_VERIFIER_GENESIS, run.get("records") or []
    for i, r in enumerate(recs):
        body = {k: v for k, v in r.items() if k not in ("record_hash", "signature_b64")}
        if _kit_verifier_sha(body) != r.get("record_hash"): problems.append(f"record {i}: record_hash does not match")
        if body.get("subject_sha256") != _kit_verifier_sha(body.get("subject")): problems.append(f"record {i}: subject_sha256 does not match")
        if pin and r.get("public_key_b64") != pin: problems.append(f"record {i}: different key than the pinned one")
        try:
            Ed25519PublicKey.from_public_bytes(_b64.b64decode(pin or r.get("public_key_b64"))).verify(
                _b64.b64decode(r.get("signature_b64", "")), str(r.get("record_hash")).encode())
        except Exception:
            problems.append(f"record {i}: signature does not verify")
        if r.get("prev_record_hash") != prev: problems.append(f"record {i}: chain link broken")
        v, checks, _ = evaluate(r.get("subject"))
        if v != r.get("verdict") or checks != r.get("checks"):
            problems.append(f"record {i}: re-running the rules gives {v}, the record says {r.get('verdict')}")
        prev = r.get("record_hash")
    if run.get("run_hash") != _kit_verifier_sha([r.get("record_hash") for r in recs]): problems.append("run_hash does not match")
    for p in problems: print("  -", p)
    if not pin: print("WARNING: no --pinned-key given; the signature was checked against the key inside the file")
    print("VERDICT:", "VERIFIED" if not problems else "TAMPERED OR INVALID", f"(CAIN-A75-054, {len(recs)} record(s), verdicts {run.get('verdicts')})")
    return 0 if not problems else 1


if __name__ == "__main__":
    _sys.exit(_kit_verifier_main(_sys.argv))
