"""CAIN-A75-074 offline verifier (rules embedded verbatim). CAIN-A75-074 international mobile-agent expansion rules. Standard library only, no CAIN imports: embedded verbatim in the
offline verifier.

A wider deployment multiplies jurisdictions, languages and device behaviours; a control that held in one market may fail on a
different app version, language or legal regime. Keep the control independent of the app surface: identity, authority and the
data boundary are checked at the action layer, and the evidence records the locale and app version. The review recomputes:

  policy       every action in every market was decided under the one action-layer policy (same SHA-256 everywhere)
  decision     re-decided here: ALLOW only when the user is verified in that market, the role permits the action, the locale
               is one of the market's locales, the device class is supported, and the data is stored in the market's residency
               region; otherwise DENY. The stated decision must equal the recomputed one
  versions     every app version in use has a passing re-test of the required suite, run by a named human, after the version
               was released and before its first action
  evidence     each action's evidence records its market, jurisdiction, locale, app version and device class, equal to the
               action's own values (portable across jurisdictions)
  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 deployment record; it does
not run the app, test a device or interpret any local law.
"""
from __future__ import annotations

import math
import re

_ID = re.compile(r"^[A-Za-z0-9_.:\-/@]{1,120}$")


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 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.mobileexpansion.review.v1":
            raise Bad("not a cain42.a75.mobileexpansion.review.v1 record")
        pol = record.get("policy") if isinstance(record.get("policy"), dict) else None
        if pol is None or not isinstance(pol.get("roles"), dict):
            raise Bad("policy with roles is required")
        markets = {}
        for m in record.get("markets") or []:
            if not isinstance(m, dict) or not isinstance(m.get("id"), str) or not isinstance(m.get("locales"), list):
                raise Bad("a market needs an id and locales")
            markets[m["id"]] = m
        users = {}
        for u in record.get("identities") or []:
            if isinstance(u, dict) and isinstance(u.get("user"), str):
                users[(u["user"], u.get("market"))] = u
        devices = record.get("supported_devices")
        if not markets or not isinstance(devices, list):
            raise Bad("markets and supported_devices are required")
        V = {}
        for v in record.get("app_versions") or []:
            if not isinstance(v, dict) or not isinstance(v.get("version"), str):
                raise Bad("an app version needs a version string")
            V[v["version"]] = v
        acts = record.get("actions")
        if not isinstance(acts, list) or not acts or not all(isinstance(a, dict) for a in acts):
            raise Bad("actions must be a non-empty list of objects")

        first_use, per_market, n_allow = {}, {}, 0
        for k, a in enumerate(acts, start=1):
            at = _num(a.get("at"), f"action {k}.at")
            first_use[a.get("app_version")] = min(first_use.get(a.get("app_version"), math.inf), at)
            m = markets.get(a.get("market"))
            per_market[str(a.get("market"))] = per_market.get(str(a.get("market")), 0) + 1
            c(f"action.{k}.policy", a.get("policy_sha256") == pol.get("sha256") and isinstance(pol.get("sha256"), str),
              f"decided under policy {str(a.get('policy_sha256'))[:12]}; deployment policy {str(pol.get('sha256'))[:12]}")
            why = []
            if m is None:
                why.append("unknown market")
            else:
                u = users.get((a.get("user"), m["id"]))
                if not (isinstance(u, dict) and u.get("verified") is True):
                    why.append("user not verified in this market")
                if a.get("locale") not in m["locales"]:
                    why.append("locale not served in this market")
                if a.get("data_region") != m.get("residency_region"):
                    why.append(f"data stored in {a.get('data_region')!r}, residency {m.get('residency_region')!r}")
            if a.get("action") not in (pol["roles"].get(a.get("role")) or []):
                why.append("role does not permit the action")
            if a.get("device_class") not in devices:
                why.append("unsupported device class")
            exp = "DENY" if why else "ALLOW"
            n_allow += exp == "ALLOW"
            c(f"action.{k}.decision", a.get("decision") == exp,
              f"{a.get('market')!r} {a.get('action')!r}: stated {a.get('decision')!r}, recomputed {exp!r}" + (f" ({'; '.join(why)})" if why else ""))
            ev = a.get("evidence") if isinstance(a.get("evidence"), dict) else {}
            fields = ("market", "locale", "app_version", "device_class")
            c(f"action.{k}.evidence", all(ev.get(f) == a.get(f) for f in fields) and m is not None and ev.get("jurisdiction") == m.get("jurisdiction"),
              f"evidence {[ev.get(f) for f in fields + ('jurisdiction',)]}")
        suite = record.get("required_suite_sha256")
        for ver, t0 in sorted(first_use.items(), key=lambda kv: str(kv[0])):
            v = V.get(ver)
            rt = v.get("retest") if isinstance(v, dict) and isinstance(v.get("retest"), dict) else {}
            ok = v is not None and rt.get("passed") is True and rt.get("suite_sha256") == suite and isinstance(rt.get("by"), str) \
                and rt["by"].startswith("human:") and isinstance(rt.get("at"), (int, float)) and not isinstance(rt.get("at"), bool) \
                and float(v.get("released_at", math.inf)) <= rt["at"] <= t0
            c(f"version.{ver}.retested", ok, f"app {ver!r} first used at {t0:g}; retest {rt.get('passed')!r} of {str(rt.get('suite_sha256'))[:12]} "
                                             f"by {rt.get('by')!r} at {rt.get('at')!r}")

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

        computed = {"same_policy_all_markets": all_ok(lambda i: i.endswith(".policy")),
                    "decisions_recomputed": all_ok(lambda i: i.endswith(".decision")),
                    "app_versions_retested": all_ok(lambda i: i.startswith("version.")),
                    "evidence_portable": all_ok(lambda i: i.endswith(".evidence"))}
        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, "actions": len(acts), "allowed": n_allow, "by_market": dict(sorted(per_market.items())),
                        "app_versions": sorted(map(str, first_use))})
    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.mobileexpansion.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-074, {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))
