"""CAIN-A75-073 offline verifier (rules embedded verbatim). CAIN-A75-073 industrial procedure knowledge rules. Standard library only, no CAIN imports: embedded verbatim in the offline
verifier.

Captured expertise is only as good as its source and its currency. A procedure that was correct five years ago can be dangerous
today, and a model's summary can lose the exception that made it safe. Bind each procedure to its expert, revision and
effective date, and keep exceptions explicit. The agent may retrieve the procedure; it may not invent the exception. The review
recomputes:

  procedures   each revision names a human expert, a source document hash, an integer revision, an effective date and a
               review-due date; its content hash equals SHA-256 of the canonical steps, preconditions and exceptions
  currency     a recommendation cites a revision that is in effect at its time: effective, not past its review date, and not
               superseded by a later revision already in effect; the cited hash equals that revision's content hash
  fidelity     the steps returned are exactly the procedure's steps in order (retrieved, not rewritten); every precondition
               is listed as checked
  exceptions   every exception whose condition holds in the recommendation's context is stated; no stated exception is
               missing from the procedure (an invented exception is refused)
  claims       every boolean the record asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the knowledge record; it does
not judge whether the procedure is technically right or inspect the plant.
"""
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}$")


class Bad(ValueError):
    pass


def content_hash(p):
    body = {"steps": p.get("steps"), "preconditions": p.get("preconditions"), "exceptions": p.get("exceptions")}
    return hashlib.sha256(json.dumps(body, 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 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") != "cain42.a75.procedure.review.v1":
            raise Bad("not a cain42.a75.procedure.review.v1 record")
        procs = record.get("procedures")
        if not isinstance(procs, list) or not procs or not all(isinstance(p, dict) for p in procs):
            raise Bad("procedures must be a non-empty list of objects")
        P = {}
        for p in procs:
            pid, rev = p.get("id"), p.get("revision")
            if not isinstance(pid, str) or not _ID.match(pid) or isinstance(rev, bool) or not isinstance(rev, int):
                raise Bad("a procedure needs an id and an integer revision")
            if (pid, rev) in P:
                raise Bad(f"duplicate procedure revision {pid} r{rev}")
            if not all(isinstance(p.get(k), list) for k in ("steps", "preconditions", "exceptions")):
                raise Bad(f"{pid} r{rev} needs steps, preconditions and exceptions lists")
            P[(pid, rev)] = p
            ef, due = _num(p.get("effective_from"), f"{pid}.effective_from"), _num(p.get("review_due"), f"{pid}.review_due")
            src = p.get("source") if isinstance(p.get("source"), dict) else {}
            k = f"procedure.{pid}.r{rev}"
            c(f"{k}.expert", isinstance(p.get("expert"), str) and p["expert"].startswith("human:") and len(p["expert"]) > 6,
              f"expert {p.get('expert')!r}")
            c(f"{k}.source", isinstance(src.get("sha256"), str) and bool(_HEX.match(src["sha256"])) and bool(src.get("doc")),
              f"source {src.get('doc')!r} committed by SHA-256")
            c(f"{k}.dates", due > ef, f"effective {ef:g}, review due {due:g}")
            c(f"{k}.content_hash", p.get("sha256") == content_hash(p), "content hash matches the steps, preconditions and exceptions")

        def current(pid, rev, at):
            p = P.get((pid, rev))
            if p is None:
                return "unknown revision"
            if at < float(p["effective_from"]):
                return "not yet in effect"
            if at >= float(p["review_due"]):
                return "past its review date"
            newer = [r for (q, r), x in P.items() if q == pid and r > rev and float(x["effective_from"]) <= at]
            return f"superseded by r{max(newer)}" if newer else None

        recs = record.get("recommendations")
        if not isinstance(recs, list) or not recs or not all(isinstance(r, dict) for r in recs):
            raise Bad("recommendations must be a non-empty list of objects")
        n_exc = 0
        for r in recs:
            rid = r.get("id") if isinstance(r.get("id"), str) and _ID.match(r["id"]) else None
            if rid is None:
                raise Bad("a recommendation needs an id")
            at = _num(r.get("at"), f"{rid}.at")
            cite = r.get("cites") if isinstance(r.get("cites"), dict) else {}
            p = P.get((cite.get("procedure"), cite.get("revision")))
            why = current(cite.get("procedure"), cite.get("revision"), at)
            c(f"rec.{rid}.current", why is None, f"cites {cite.get('procedure')!r} r{cite.get('revision')!r}" + (f": {why}" if why else " in effect"))
            if p is None:
                continue
            c(f"rec.{rid}.cited_hash", cite.get("sha256") == p.get("sha256") == content_hash(p), "cited content hash equals the procedure")
            c(f"rec.{rid}.steps_verbatim", r.get("steps_returned") == p["steps"],
              "steps returned exactly as written, in order" if r.get("steps_returned") == p["steps"] else "steps rewritten, reordered, added or dropped")
            chk = r.get("preconditions_checked") if isinstance(r.get("preconditions_checked"), list) else []
            miss = [x for x in p["preconditions"] if x not in chk]
            c(f"rec.{rid}.preconditions", not miss, f"preconditions not checked {miss}" if miss else "every precondition checked")
            ctx = set((r.get("context") or {}).get("conditions") or [])
            ex = {e.get("id"): e for e in p["exceptions"] if isinstance(e, dict)}
            due = sorted(i for i, e in ex.items() if e.get("condition") in ctx)
            stated = r.get("exceptions_stated") if isinstance(r.get("exceptions_stated"), list) else []
            dropped, invented = [i for i in due if i not in stated], [i for i in stated if i not in ex]
            n_exc += len(due)
            c(f"rec.{rid}.exceptions_kept", not dropped, f"triggered exceptions not stated {dropped}" if dropped else f"triggered exceptions stated {due}")
            c(f"rec.{rid}.no_invented_exception", not invented, f"exceptions not in the procedure {invented}" if invented else "no invented exception")

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

        computed = {"procedures_bound": all_ok(lambda i: i.startswith("procedure.")),
                    "current_revisions_cited": all_ok(lambda i: i.endswith((".current", ".cited_hash"))),
                    "retrieved_not_rewritten": all_ok(lambda i: i.endswith((".steps_verbatim", ".preconditions"))),
                    "exceptions_explicit": all_ok(lambda i: i.endswith((".exceptions_kept", ".no_invented_exception")))}
        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}")
        summary.update({"computed": computed, "procedures": len(P), "recommendations": len(recs), "exceptions_triggered": n_exc})
    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.procedure.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-073, {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))
