"""CAIN-A75-023 offline verifier (rules embedded verbatim). CAIN-A75-023 vulnerability-to-patch rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

An agent that finds a vulnerability and writes its own fix must not also be the one who says the fix works. The review recomputes
a find-fix-prove campaign, finding by finding:

  detected     the finding names a rule, a safe relative file path, the file's SHA-256 before the fix and the digest of the run of
               a named, versioned, deterministic detector on the base tree
  patch        a fixed finding has a named patch author, a diff digest, changed files inside the declared scope that include the
               vulnerable file, and a file digest that actually changed
  proof        the proving test was written by someone other than the patch author, was not edited by the patch, failed on the
               base tree and passed on the patched tree
  rescan       the same detector version, run on the patched tree, no longer reports the finding
  regression   the suite did not shrink: no test removed, no fewer tests, no fewer passing, no more failing
  approval     a named human who is not the patch author approved that exact diff
  not fixed    an open finding has a named human owner and a due time; an accepted risk has a named human, a reason and an expiry
  published    the published fixed / open / accepted counts equal the recomputation; claims match what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the campaign record; it does
not run the detector or the tests, and a proof is only as strong as the test that was written.
"""
from __future__ import annotations

import math
import re

_HEX = re.compile(r"^[0-9a-f]{64}$")
SCHEMA = "cain42.a75.vulnpatch.review.v1"
STATUSES = ("fixed", "open", "accepted_risk")
MAX_FINDINGS = 2000


class Bad(ValueError):
    pass


def _hex(v):
    return isinstance(v, str) and bool(_HEX.match(v))


def _who(v, kinds=("human", "agent", "tool", "org")):
    return isinstance(v, str) and ":" in v and v.split(":", 1)[0] in kinds and bool(v.split(":", 1)[1])


def _num(v):
    return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)


def _safe(p):
    return isinstance(p, str) and bool(p) and not p.startswith("/") and "\\" not in p and ".." not in p.split("/")


def _in_scope(scope, path):
    return any(s == path or (s.endswith("/") and path.startswith(s)) for s in scope if isinstance(s, str))


def _count(d, k):
    v = d.get(k) if isinstance(d, dict) else None
    return v if isinstance(v, int) and not isinstance(v, bool) and v >= 0 else None


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

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

    try:
        if not isinstance(record, dict) or record.get("schema") != SCHEMA:
            raise Bad(f"not a {SCHEMA} record")
        det, repo, findings = record.get("detector"), record.get("repo"), record.get("findings")
        if not isinstance(det, dict) or not isinstance(repo, dict) or not isinstance(findings, list) or not findings or len(findings) > MAX_FINDINGS:
            raise Bad(f"detector, repo and 1 to {MAX_FINDINGS} findings are required")
        base = repo.get("base_tree_sha256")
        c("detector.deterministic", isinstance(det.get("name"), str) and bool(det.get("name")) and isinstance(det.get("version"), str)
          and bool(det.get("version")) and det.get("deterministic") is True and _hex(base),
          f"{det.get('name')!r} {det.get('version')!r}, deterministic {det.get('deterministic')!r}, base tree {str(base)[:16]}")
        tally, ids = {s: 0 for s in STATUSES}, set()
        for f in findings:
            if not isinstance(f, dict) or not isinstance(f.get("id"), str) or not f["id"] or f["id"] in ids:
                raise Bad("every finding needs a unique id")
            ids.add(f["id"])
            if f.get("status") not in STATUSES:
                raise Bad(f"{f['id']}.status must be one of {list(STATUSES)}")
            k, st = f"finding.{f['id']}", f["status"]
            tally[st] += 1
            c(f"{k}.detected", isinstance(f.get("rule"), str) and bool(f.get("rule")) and _safe(f.get("file")) and _hex(f.get("file_sha256_before"))
              and _hex(f.get("detector_run_sha256")), f"rule {f.get('rule')!r} in {f.get('file')!r}")
            if st == "open":
                o = f.get("open") if isinstance(f.get("open"), dict) else {}
                c(f"{k}.owned", _who(o.get("owner"), ("human",)) and _num(o.get("due_at")), f"owner {o.get('owner')!r}, due {o.get('due_at')!r}")
                continue
            if st == "accepted_risk":
                a = f.get("acceptance") if isinstance(f.get("acceptance"), dict) else {}
                c(f"{k}.risk_accepted", _who(a.get("by"), ("human",)) and isinstance(a.get("reason"), str) and len(a.get("reason", "").strip()) >= 10
                  and _num(a.get("expires_at")), f"accepted by {a.get('by')!r} until {a.get('expires_at')!r}")
                continue
            p, pr = f.get("patch"), f.get("proof")
            rs, rg, ap = f.get("rescan"), f.get("regression"), f.get("approval")
            if not all(isinstance(x, dict) for x in (p, pr, rs, rg, ap)):
                raise Bad(f"{f['id']}: a fixed finding needs patch, proof, rescan, regression and approval")
            files = p.get("files") if isinstance(p.get("files"), list) else []
            scope = p.get("scope") if isinstance(p.get("scope"), list) else []
            changed = {x.get("path"): x.get("sha256_after") for x in files if isinstance(x, dict) and isinstance(x.get("path"), str)}
            out = sorted(x for x in changed if not _safe(x) or not _in_scope(scope, x))
            c(f"{k}.patch", _who(p.get("author")) and _hex(p.get("diff_sha256")) and _hex(p.get("tree_sha256_after")) and p.get("tree_sha256_after") != base
              and bool(changed) and not out and f.get("file") in changed and _hex(changed.get(f.get("file")))
              and changed.get(f.get("file")) != f.get("file_sha256_before"),
              f"by {p.get('author')!r}, {len(changed)} files" + (f", outside scope: {out}" if out else "")
              + ("" if f.get("file") in changed else ", the vulnerable file was not changed"))
            c(f"{k}.independent_test", _who(pr.get("test_author")) and pr.get("test_author") != p.get("author") and _hex(pr.get("test_sha256"))
              and _safe(pr.get("test_path")) and pr.get("test_path") not in changed and pr.get("on_base") == "FAIL" and pr.get("on_patched") == "PASS"
              and pr.get("base_tree_sha256") == base and pr.get("patched_tree_sha256") == p.get("tree_sha256_after"),
              f"test by {pr.get('test_author')!r} (patch by {p.get('author')!r}): base {pr.get('on_base')!r}, patched {pr.get('on_patched')!r}"
              + (", the patch edited the test" if pr.get("test_path") in changed else ""))
            c(f"{k}.rescan_clean", rs.get("detector_version") == det.get("version") and rs.get("finding_present") is False
              and rs.get("tree_sha256") == p.get("tree_sha256_after") and _hex(rs.get("run_sha256")),
              f"detector {rs.get('detector_version')!r} on tree {str(rs.get('tree_sha256'))[:16]}: finding present {rs.get('finding_present')!r}")
            b, a = rg.get("before"), rg.get("after")
            nums = [_count(b, x) for x in ("total", "passed", "failed")] + [_count(a, x) for x in ("total", "passed", "failed")]
            ok_rg = None not in nums and nums[1] + nums[2] <= nums[0] and nums[4] + nums[5] <= nums[3] and nums[3] >= nums[0] and nums[4] >= nums[1] \
                and nums[5] <= nums[2] and rg.get("tests_removed") == []
            c(f"{k}.no_regression", ok_rg, f"before total/passed/failed {nums[:3]}, after {nums[3:]}, removed {rg.get('tests_removed')!r}")
            c(f"{k}.approved", _who(ap.get("by"), ("human",)) and ap.get("by") != p.get("author") and ap.get("diff_sha256") == p.get("diff_sha256")
              and _num(ap.get("at")), f"approved by {ap.get('by')!r} for diff {str(ap.get('diff_sha256'))[:16]}")
        pub = record.get("published") if isinstance(record.get("published"), dict) else {}
        c("published.counts", all(pub.get(s) == tally[s] and not isinstance(pub.get(s), bool) for s in STATUSES),
          f"stated {[pub.get(s) for s in STATUSES]}, recomputed {[tally[s] for s in STATUSES]}")

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

        computed = {"detection_deterministic": all_ok(lambda i: i.startswith("detector.") or i.endswith(".detected")),
                    "fixes_proved_independently": all_ok(lambda i: i.endswith((".independent_test", ".rescan_clean", ".no_regression"))),
                    "patches_scoped_and_approved": all_ok(lambda i: i.endswith((".patch", ".approved"))),
                    "unfixed_findings_owned": all_ok(lambda i: i.endswith((".owned", ".risk_accepted"))),
                    "counts_match": all_ok(lambda i: i.startswith("published."))}
        claims = record.get("claims") if isinstance(record.get("claims"), dict) else {}
        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}")
        proved = sum(1 for f in findings if f["status"] == "fixed" and all(
            x["ok"] for x in checks if x["id"].startswith(f"finding.{f['id']}.")))
        summary.update({"computed": computed, "findings": len(findings), "fixed": tally["fixed"], "fixed_and_proved": proved,
                        "open": tally["open"], "accepted_risk": tally["accepted_risk"], "detector": f"{det.get('name')} {det.get('version')}"})
    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.vulnpatch.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-023, {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))
