"""CAIN-A75-045 offline verifier (rules embedded verbatim). CAIN-A75-045 approval-gated remediation rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

An IT agent investigated an incident and repaired it. The package claims the repair was approved. The review recomputes it:

  diagnosis   the diagnosis cites hashed telemetry captured before it was made; it executes nothing
  action      every remediation action names an allowed type and an allowed target, follows the diagnosis it cites, and its
              digest equals SHA-256 of the canonical {type, target, params} recomputed here
  approval    a named human other than the proposer accepted that exact digest and target, after the proposal, with an
              expiry inside the policy's maximum lease; dual-approval action types need two distinct humans
  execution   each approved action ran exactly once, inside its approval window, with the approved digest and target;
              nothing ran without an approval
  effect      a hashed post-execution observation, taken after the execution, meets the expected threshold
  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 incident record; it does not connect to the estate or re-run the repair.
"""
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}$")
ACTION_TYPES = {"restart", "rollback", "patch", "scale", "config_change", "failover"}
OPS = {"<=", ">=", "=="}


class Bad(ValueError):
    pass


def action_digest(action):
    body = {"type": action.get("type"), "target": action.get("target"), "params": action.get("params")}
    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 _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 _meets(observed, op, threshold):
    return {"<=": observed <= threshold, ">=": observed >= threshold, "==": observed == threshold}[op]


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

    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.remediation.incident.v1":
            raise Bad("not a cain42.a75.remediation.incident.v1 record")
        pol, diag = record.get("policy"), record.get("diagnosis")
        if not isinstance(pol, dict) or not isinstance(diag, dict):
            raise Bad("policy and diagnosis must be objects")
        allowed_types = pol.get("allowed_actions")
        allowed_targets = pol.get("allowed_targets")
        if not isinstance(allowed_types, list) or not allowed_types or not set(allowed_types) <= ACTION_TYPES:
            raise Bad("policy.allowed_actions must be a non-empty subset of the known action types")
        if not isinstance(allowed_targets, list) or not allowed_targets:
            raise Bad("policy.allowed_targets must be a non-empty list")
        max_ttl = _num(pol.get("max_approval_ttl_s"), "policy.max_approval_ttl_s", 1.0, 86400.0)
        dual = set(pol.get("dual_approval_actions") or [])

        # ---- diagnosis
        telemetry = record.get("telemetry")
        if not isinstance(telemetry, list) or not telemetry:
            raise Bad("telemetry must be a non-empty list")
        T = {}
        for t in telemetry:
            if not isinstance(t, dict):
                raise Bad("a telemetry item must be an object")
            tid = _id(t.get("id"), "telemetry.id")
            if tid in T:
                raise Bad(f"duplicate telemetry {tid}")
            T[tid] = t
            c(f"telemetry.{tid}.hash", isinstance(t.get("sha256"), str) and bool(_HEX.match(t["sha256"])), "content hash")
            _num(t.get("captured_at"), f"telemetry.{tid}.captured_at")
        diag_id = _id(diag.get("id"), "diagnosis.id")
        diag_at = _num(diag.get("made_at"), "diagnosis.made_at")
        cited = diag.get("evidence")
        if not isinstance(cited, list):
            raise Bad("diagnosis.evidence must be a list")
        good_cites = [e for e in cited if e in T and isinstance(T[e].get("sha256"), str) and _HEX.match(T[e]["sha256"])
                      and _num(T[e].get("captured_at"), "telemetry.captured_at") <= diag_at + 1e-9]
        c("diagnosis.evidence", len(good_cites) >= 1 and len(good_cites) == len(cited),
          f"{len(good_cites)}/{len(cited)} cited telemetry hashed and captured before the diagnosis")
        c("diagnosis.no_execution", not diag.get("executed_actions"), "the diagnosis step executed nothing")

        # ---- actions, approvals, executions
        actions = record.get("actions")
        if not isinstance(actions, list) or not actions:
            raise Bad("actions must be a non-empty list")
        approvals, executions = record.get("approvals"), record.get("executions")
        if not isinstance(approvals, list) or not isinstance(executions, list):
            raise Bad("approvals and executions must be lists")
        A = {}
        for a in actions:
            if not isinstance(a, dict):
                raise Bad("an action must be an object")
            aid = _id(a.get("id"), "action.id")
            if aid in A:
                raise Bad(f"duplicate action {aid}")
            A[aid] = a
        for e in executions:
            if not isinstance(e, dict) or e.get("action_id") not in A:
                c("execution.known_action", False, f"execution of unknown action {e.get('action_id') if isinstance(e, dict) else e!r}")

        ok_actions, verified_effects = 0, 0
        for aid in sorted(A):
            a = A[aid]
            digest = action_digest(a)
            proposed_at = _num(a.get("proposed_at"), f"{aid}.proposed_at")
            c(f"{aid}.type", a.get("type") in allowed_types, f"type {a.get('type')!r}")
            c(f"{aid}.target", a.get("target") in allowed_targets, f"target {a.get('target')!r}")
            c(f"{aid}.params", isinstance(a.get("params"), dict), "params are an object")
            c(f"{aid}.digest", a.get("digest") == digest, f"stated digest matches recomputed {digest[:12]}")
            c(f"{aid}.follows_diagnosis", a.get("diagnosis_id") == diag_id and proposed_at >= diag_at - 1e-9,
              "cites the diagnosis and was proposed after it")
            need = 2 if a.get("type") in dual else 1
            valid = []
            for ap in approvals:
                if not isinstance(ap, dict) or ap.get("action_id") != aid:
                    continue
                at = _num(ap.get("approved_at"), f"{aid}.approval.approved_at")
                exp = _num(ap.get("expires_at"), f"{aid}.approval.expires_at")
                who = ap.get("by")
                tag = f"{aid}.approval.{who}"
                ok = True
                for cid, cond, det in (
                        (f"{tag}.human", _human(who), f"approver {who!r} is a named human"),
                        (f"{tag}.independent", who != a.get("proposed_by"), "approver is not the proposer"),
                        (f"{tag}.decision", ap.get("decision") == "accept", f"decision {ap.get('decision')!r}"),
                        (f"{tag}.digest", ap.get("action_digest") == digest, "approval bound to the exact action digest"),
                        (f"{tag}.target", ap.get("target") == a.get("target"), "approval bound to the action target"),
                        (f"{tag}.after_proposal", at >= proposed_at - 1e-9, "approved after the proposal"),
                        (f"{tag}.ttl", at < exp <= at + max_ttl + 1e-9, f"expiry within {max_ttl}s of approval")):
                    c(cid, cond, det)
                    ok = ok and bool(cond)
                if ok:
                    valid.append(ap)
            humans = {ap["by"] for ap in valid}
            c(f"{aid}.approved", len(humans) >= need, f"{len(humans)} valid distinct human approval(s) >= {need}")
            runs = [e for e in executions if isinstance(e, dict) and e.get("action_id") == aid]
            if not runs:
                summary["actions"][aid] = {"digest": digest, "approvals": len(humans), "executed": 0}
                continue
            c(f"{aid}.executed_once", len(runs) == 1, f"executed {len(runs)} time(s)")
            ex = runs[0]
            ex_at = _num(ex.get("executed_at"), f"{aid}.executed_at")
            c(f"{aid}.execution.authorized", len(humans) >= need, "executed only with the required approval")
            c(f"{aid}.execution.window", any(ap["approved_at"] <= ex_at <= ap["expires_at"] for ap in valid) if valid else False,
              "executed inside an approval window")
            c(f"{aid}.execution.digest", ex.get("action_digest") == digest, "executed the approved digest")
            c(f"{aid}.execution.target", ex.get("target") == a.get("target"), "executed on the approved target")
            obs = ex.get("observation")
            if not isinstance(obs, dict):
                raise Bad(f"{aid}: an execution needs an observation")
            op = obs.get("op")
            if op not in OPS:
                raise Bad(f"{aid}.observation.op must be one of {sorted(OPS)}")
            observed = _num(obs.get("observed"), f"{aid}.observation.observed", -1e15)
            threshold = _num(obs.get("threshold"), f"{aid}.observation.threshold", -1e15)
            c(f"{aid}.effect.hash", isinstance(obs.get("sha256"), str) and bool(_HEX.match(obs["sha256"])), "observation hash")
            c(f"{aid}.effect.after", _num(obs.get("observed_at"), f"{aid}.observation.observed_at") > ex_at, "observed after execution")
            met = _meets(observed, op, threshold)
            c(f"{aid}.effect.met", met, f"{obs.get('metric')!r}: {observed} {op} {threshold}")
            summary["actions"][aid] = {"digest": digest, "approvals": len(humans), "executed": len(runs), "effect_met": met}
            ok_actions += 1
            verified_effects += int(met)

        claims = record.get("claims") if isinstance(record.get("claims"), dict) else {}
        failed_so_far = [x for x in checks if not x["ok"]]
        computed = {
            "diagnosis_evidenced": all(x["ok"] for x in checks if x["id"].startswith(("diagnosis.", "telemetry."))),
            "all_actions_approved": all(x["ok"] for x in checks if ".approved" in x["id"] or ".approval." in x["id"]
                                        or (x["id"].endswith((".digest", ".target", ".type")) and ".execution." not in x["id"])),
            "executed_once_within_window": all(x["ok"] for x in checks if ".execution." in x["id"] or x["id"].endswith(".executed_once")
                                               or x["id"] == "execution.known_action"),
            "effect_verified": ok_actions > 0 and verified_effects == ok_actions
                               and all(x["ok"] for x in checks if ".effect." in x["id"]),
        }
        for key in sorted(claims):
            c(f"claims.{key}", key in computed and claims[key] == computed[key], f"claimed {claims[key]!r}, computed {computed.get(key)!r}")
        summary["computed"] = computed
        summary["failed_before_claims"] = len(failed_so_far)
    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.remediation.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-045, {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))
