"""CAIN-A75-017 offline verifier (rules embedded verbatim). CAIN-A75-017 portable skill rules. Standard library only, no CAIN imports: embedded verbatim in the offline verifier.

A portable skill is someone else's code with a manifest. The manifest is a claim; what the code was seen to do is evidence; what
the skill is allowed to do at run time is a grant. The review recomputes all three against one exact package:

  package      the package digest is the SHA-256 of its sorted (path, file digest) list; paths are relative and unique; the
               manifest names an author, a version and what the skill declares: tools, network hosts, file paths, environment
               variables, data scopes and whether it runs a shell
  static scan  the scan is bound to that digest; every tool, host, path and variable it observed is declared; a shell is used
               only if declared; dynamic code loading (eval, exec, unpickling) is never accepted
  sandbox run  the run is bound to that digest, ran with network denied by default, and observed nothing undeclared
  review       a named human who is not the author approved that digest
  grant        a named human granted that digest, after the review, for a limited time, and the grant never exceeds the manifest
  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 record; it does not
execute the skill, and a capability that neither the scan nor the sandbox run observed is not proven absent.
"""
from __future__ import annotations

import hashlib
import json
import math
import re

_HEX = re.compile(r"^[0-9a-f]{64}$")
_VER = re.compile(r"^\d+\.\d+\.\d+$")
SCHEMA = "cain42.a75.skillreview.review.v1"
CATS = ("tools", "network", "filesystem", "env")
MAX_FILES = 2000


class Bad(ValueError):
    pass


def package_sha256(files):
    """SHA-256 over the sorted [path, sha256] pairs of the package."""
    pairs = sorted([f.get("path"), f.get("sha256")] for f in files)
    return hashlib.sha256(json.dumps(pairs, separators=(",", ":"), ensure_ascii=True).encode()).hexdigest()


def _strs(v, what, empty_ok=True):
    if not isinstance(v, list) or not all(isinstance(x, str) and x for x in v) or (not v and not empty_ok):
        raise Bad(f"{what} must be a list of non-empty strings")
    return v


def _human(v):
    return isinstance(v, str) and v.startswith("human:") and len(v) > 6


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 _host_ok(declared, h):
    return any(d == h or (d.startswith("*.") and h.endswith(d[1:]) and len(h) > len(d) - 1) for d in declared)


def _path_ok(declared, p):
    return any(d == p or (d.endswith("/") and p.startswith(d)) for d in declared)


def _undeclared(cat, declared, observed):
    if cat == "network":
        return sorted(x for x in observed if not _host_ok(declared, x))
    if cat == "filesystem":
        return sorted(x for x in observed if not _path_ok(declared, x))
    return sorted(set(observed) - set(declared))


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")
        skill = record.get("skill")
        if not isinstance(skill, dict) or not isinstance(skill.get("manifest"), dict):
            raise Bad("skill and skill.manifest are required")
        files, man = skill.get("files"), skill["manifest"]
        if not isinstance(files, list) or not files or len(files) > MAX_FILES or not all(isinstance(f, dict) for f in files):
            raise Bad(f"skill.files must list 1 to {MAX_FILES} files")
        declared = {cat: _strs(man.get(cat), f"manifest.{cat}") for cat in CATS}
        scopes = _strs(man.get("data_scopes"), "manifest.data_scopes")
        if not isinstance(man.get("shell"), bool):
            raise Bad("manifest.shell must be true or false")
        paths = [f.get("path") for f in files]
        digest = package_sha256(files) if all(isinstance(p, str) for p in paths) and all(isinstance(f.get("sha256"), str) for f in files) else None
        c("package.files", all(_safe(p) for p in paths) and len(set(map(str, paths))) == len(paths) and all(bool(_HEX.match(str(f.get("sha256")))) for f in files),
          f"{len(files)} files; safe relative unique paths with SHA-256 digests required")
        c("package.digest", digest is not None and skill.get("package_sha256") == digest,
          f"stated {str(skill.get('package_sha256'))[:16]}, recomputed {str(digest)[:16]}")
        c("package.manifest", isinstance(skill.get("name"), str) and bool(skill.get("name")) and isinstance(skill.get("author"), str)
          and ":" in skill.get("author", "") and bool(_VER.match(str(skill.get("version")))),
          f"name {skill.get('name')!r}, author {skill.get('author')!r}, version {skill.get('version')!r}")
        undeclared_all = []
        for stage in ("static_scan", "sandbox_run"):
            st = record.get(stage)
            if not isinstance(st, dict) or not isinstance(st.get("observed"), dict):
                raise Bad(f"{stage} with an observed section is required")
            obs = st["observed"]
            who = st.get("analyzer") if stage == "static_scan" else st.get("sandbox")
            c(f"{stage}.bound", digest is not None and st.get("package_sha256") == digest and isinstance(who, str) and bool(who),
              f"run by {who!r} on package {str(st.get('package_sha256'))[:16]}")
            for cat in CATS:
                und = _undeclared(cat, declared[cat], _strs(obs.get(cat), f"{stage}.observed.{cat}"))
                undeclared_all += [f"{cat}:{x}" for x in und]
                c(f"{stage}.{cat}.declared", not und, f"observed but not declared: {und}" if und else f"{len(obs[cat])} observed, all declared")
            c(f"{stage}.shell", obs.get("shell") is False or (obs.get("shell") is True and man["shell"]),
              f"shell observed {obs.get('shell')!r}, declared {man['shell']!r}")
            if stage == "static_scan":
                c("static_scan.dynamic_code", obs.get("dynamic_code") is False, f"dynamic code loading observed: {obs.get('dynamic_code')!r}")
            else:
                c("sandbox_run.default_deny", st.get("network_default") == "deny", f"network default {st.get('network_default')!r}")
        rev = record.get("review") if isinstance(record.get("review"), dict) else {}
        c("review.independent", _human(rev.get("reviewer")) and rev.get("reviewer") != skill.get("author") and rev.get("decision") == "approved"
          and digest is not None and rev.get("package_sha256") == digest and _num(rev.get("at")),
          f"{rev.get('decision')!r} by {rev.get('reviewer')!r} for package {str(rev.get('package_sha256'))[:16]}")
        g = record.get("grant") if isinstance(record.get("grant"), dict) else {}
        c("grant.bound", _human(g.get("by")) and digest is not None and g.get("package_sha256") == digest and _num(g.get("issued_at"))
          and _num(g.get("expires_at")) and _num(rev.get("at")) and rev["at"] <= g["issued_at"] < g["expires_at"],
          f"by {g.get('by')!r} for package {str(g.get('package_sha256'))[:16]}, {g.get('issued_at')!r}..{g.get('expires_at')!r}, review at {rev.get('at')!r}")
        for cat, limit in (("tools", declared["tools"]), ("network", declared["network"]), ("data_scopes", scopes)):
            over = _undeclared(cat, limit, _strs(g.get(cat), f"grant.{cat}"))
            c(f"grant.{cat}.within_manifest", not over, f"granted beyond the manifest: {over}" if over else f"{len(g[cat])} granted of {len(limit)} declared")

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

        computed = {"package_pinned": all_ok(lambda i: i.startswith("package.") or i.endswith(".bound")),
                    "behaviour_matches_manifest": all_ok(lambda i: i.startswith(("static_scan.", "sandbox_run.")) and not i.endswith(".bound")),
                    "independently_reviewed": all_ok(lambda i: i.startswith("review.")),
                    "grant_within_manifest": all_ok(lambda i: i.startswith("grant."))}
        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, "files": len(files), "package_sha256": digest,
                        "declared": {cat: len(declared[cat]) for cat in CATS}, "undeclared": sorted(set(undeclared_all)),
                        "granted_tools": len(g.get("tools") or []), "shell_declared": man["shell"]})
    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.skillreview.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-017, {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))
