"""CAIN-A75-075 offline verifier (rules embedded verbatim). CAIN-A75-075 delegation measurement rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

Estimated task size is not verified time saved, and adoption is not control. The useful measurement is what was delegated,
under what authority, with what result and what rework. Measure the delegated unit, not the anecdote: task, authority,
duration, result, rework and reviewer. The review recomputes a delegation study:

  units        each delegated unit names its task by SHA-256, a delegating human, the agent, and a grant that covers the task
               kind and was valid when the unit started
  observed     each unit's duration is recomputed from its run record (same agent, start and end), not taken from the summary
  outcome      each unit has a result (accepted / reworked / rejected) and a named human reviewer who is not the agent; a
               reworked unit records the human rework minutes and who did it
  separation   estimated effort and observed effort are reported separately; "time saved" is computed only over units with an
               observed human baseline (baseline minutes - agent minutes - rework minutes) and is labelled observed; a time
               saved figure based on estimates must be labelled estimated
  published    the published counts, rework rate, observed agent minutes, rework minutes, estimated minutes and time saved
               equal the recomputation, and the measurement method is published with the result
  claims       every boolean the study asserts matches what this review computed

Verdict: SOUND, else UNSOUND with every failing check named. Malformed input is UNSOUND. It reviews the study record; it does
not observe anyone working or verify that the run records are complete.
"""
from __future__ import annotations

import math
import re

_HEX = re.compile(r"^[0-9a-f]{64}$")
RESULTS = ("accepted", "reworked", "rejected")


class Bad(ValueError):
    pass


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 _human(p):
    return isinstance(p, str) and p.startswith("human:") and len(p) > 6


def _close(a, b):
    return isinstance(a, (int, float)) and not isinstance(a, bool) and abs(a - b) <= 0.05


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.delegation.review.v1":
            raise Bad("not a cain42.a75.delegation.review.v1 record")
        grants = record.get("grants") if isinstance(record.get("grants"), dict) else None
        runs = record.get("run_records") if isinstance(record.get("run_records"), dict) else None
        units = record.get("units")
        if grants is None or runs is None or not isinstance(units, list) or not units or not all(isinstance(u, dict) for u in units):
            raise Bad("grants, run_records and a non-empty units list are required")
        tot = {"units": 0, "accepted": 0, "reworked": 0, "rejected": 0, "agent_minutes": 0.0, "rework_minutes": 0.0,
               "estimated_minutes": 0.0, "saved_observed": 0.0, "baseline_units": 0}
        for u in units:
            uid = u.get("id") if isinstance(u.get("id"), str) else None
            if uid is None:
                raise Bad("a unit needs an id")
            k = f"unit.{uid}"
            tot["units"] += 1
            g = grants.get(u.get("grant"))
            start = _num(u.get("started_at"), f"{uid}.started_at")
            c(f"{k}.authorised", _hex(u.get("task_sha256")) and _human(u.get("delegated_by")) and isinstance(g, dict)
              and g.get("by") == u.get("delegated_by") and u.get("task_kind") in (g.get("task_kinds") or [])
              and float(g.get("valid_from", math.inf)) <= start < float(g.get("valid_to", -1)),
              f"task by {u.get('delegated_by')!r} under grant {u.get('grant')!r} for {u.get('task_kind')!r}")
            rr = runs.get(u.get("run_record_sha256")) if isinstance(u.get("run_record_sha256"), str) else None
            ok_rr = isinstance(rr, dict) and rr.get("agent") == u.get("agent") and rr.get("started_at") == u.get("started_at") \
                and isinstance(rr.get("ended_at"), (int, float)) and not isinstance(rr.get("ended_at"), bool) and rr["ended_at"] >= start
            c(f"{k}.run_record", ok_rr, f"run record {str(u.get('run_record_sha256'))[:12]} for {u.get('agent')!r}")
            minutes = (float(rr["ended_at"]) - start) / 60.0 if ok_rr else 0.0
            c(f"{k}.observed_duration", ok_rr and _close(u.get("agent_minutes"), minutes),
              f"stated {u.get('agent_minutes')!r} min, run record {round(minutes, 2)} min")
            tot["agent_minutes"] += minutes
            res = u.get("result")
            c(f"{k}.reviewed", res in RESULTS and _human(u.get("reviewer")) and u.get("reviewer") != u.get("agent"),
              f"result {res!r}, reviewer {u.get('reviewer')!r}")
            if res in RESULTS:
                tot[res] += 1
            rw = u.get("rework") if isinstance(u.get("rework"), dict) else None
            if res == "reworked":
                rm = rw.get("minutes") if rw else None
                c(f"{k}.rework", rw is not None and isinstance(rm, (int, float)) and not isinstance(rm, bool) and rm > 0 and _human(rw.get("by")),
                  f"rework {rw.get('minutes')!r} min by {rw.get('by')!r}" if rw else "no rework recorded")
                tot["rework_minutes"] += float(rm) if isinstance(rm, (int, float)) and not isinstance(rm, bool) else 0.0
            else:
                c(f"{k}.rework", rw is None, "no rework recorded for a unit that was not reworked" if rw is None
                  else f"unexpected rework of {rw.get('minutes')!r} min on a {res!r} unit")
            est = _num(u.get("estimated_minutes"), f"{uid}.estimated_minutes")
            tot["estimated_minutes"] += est
            base = u.get("baseline_observed_minutes")
            if base is not None and res in ("accepted", "reworked"):
                tot["saved_observed"] += _num(base, f"{uid}.baseline") - minutes - (float(rw["minutes"]) if res == "reworked" and rw else 0.0)
                tot["baseline_units"] += 1
        pub = record.get("published") if isinstance(record.get("published"), dict) else {}
        want = {"units": tot["units"], "accepted": tot["accepted"], "reworked": tot["reworked"], "rejected": tot["rejected"]}
        c("published.counts", all(pub.get(x) == y for x, y in want.items()), f"stated {[pub.get(x) for x in want]}, recomputed {list(want.values())}")
        rate = round(tot["reworked"] / tot["units"], 4)
        c("published.rework_rate", _close(pub.get("rework_rate"), rate), f"stated {pub.get('rework_rate')!r}, recomputed {rate}")
        for key in ("agent_minutes", "rework_minutes", "estimated_minutes"):
            c(f"published.{key}", _close(pub.get(key), round(tot[key], 2)), f"stated {pub.get(key)!r}, recomputed {round(tot[key], 2)}")
        ts = pub.get("time_saved") if isinstance(pub.get("time_saved"), dict) else {}
        if ts.get("basis") == "observed":
            c("separation.time_saved", tot["baseline_units"] > 0 and _close(ts.get("minutes"), round(tot["saved_observed"], 2))
              and ts.get("units") == tot["baseline_units"],
              f"observed time saved stated {ts.get('minutes')!r} over {ts.get('units')!r} units; recomputed {round(tot['saved_observed'], 2)} "
              f"over {tot['baseline_units']} units with a measured baseline")
        elif ts.get("basis") == "estimated":
            c("separation.time_saved", True, "time saved labelled as an estimate")
        else:
            c("separation.time_saved", not ts, f"time saved without a basis {ts!r}" if ts else "no time-saved figure published")
        m = record.get("method") if isinstance(record.get("method"), dict) else {}
        c("published.method", all(isinstance(m.get(x), str) and m[x].strip() for x in ("unit_definition", "estimate_method", "sample")),
          f"method {sorted(m)}")

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

        computed = {"units_authorised": all_ok(lambda i: i.endswith(".authorised")),
                    "durations_observed": all_ok(lambda i: i.endswith((".run_record", ".observed_duration"))),
                    "outcomes_reviewed": all_ok(lambda i: i.endswith((".reviewed", ".rework"))),
                    "estimates_separated": all_ok(lambda i: i.startswith("separation.")),
                    "method_published": 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}")
        summary.update({"computed": computed, "units": tot["units"], "rework_rate": rate, "agent_minutes": round(tot["agent_minutes"], 2),
                        "estimated_minutes": round(tot["estimated_minutes"], 2), "observed_time_saved": round(tot["saved_observed"], 2),
                        "baseline_units": tot["baseline_units"]})
    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


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


# ---------------------------------------------------------------------------- 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.delegation.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-075, {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))
