"""
Verifiable inference: commit to a model call now, prove it later (docs/verifiable-inference.md).

    from riskrouter_recorder import Recorder
    from riskrouter_recorder.inference import model_digest, commit_inference, check_inference

    recorder = Recorder(journal="evidence.jsonl")
    MODEL = model_digest(["weights/model-00001.safetensors", "weights/config.json"])   # once per version
    commit_inference(recorder, system_ref="claims-assistant", model_digest=MODEL, input=prompt, output=answer,
                     decoding="vllm 0.6.3; temperature 0; seed 7",
                     attestation={"kind": "nvidia-cc-gpu", "token": token})

Only hashes are taken on the agent's path (microseconds); the weights, the prompt and the
answer never leave you, and only the record's salted digest is sent. The proof follows by
re-execution, by a confidential-computing attestation requested with this call's nonce, or by
a proof file checked with its own proof system. check_inference never verifies an
attestation's signature: that is the hardware vendor's verifier's work.

The same construction as recorders/js/inference.mjs, held to spec-vectors.json byte for byte.
"""
import base64
import datetime
import hashlib
import json
import os
import re
import uuid

KIND = "ai.inference"
PACK = "ai-act"
PACK_VERSION = 1
MODEL_FORMAT = "riskrouter-inference-model|1"
NONCE_FORMAT = "riskrouter-inference-nonce|1"
ATTESTATION_KINDS = ("none", "nvidia-cc-gpu", "amd-sev-snp", "intel-tdx", "other")
_DIGEST = re.compile(r"^[0-9a-f]{64}\Z")


def _sha256(data):
    return hashlib.sha256(data.encode("utf-8") if isinstance(data, str) else bytes(data)).hexdigest()


def _file_sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def model_digest_of_manifest(manifest):
    """The model digest (frozen) from [{"name": ..., "sha256": ...}], in any order."""
    if not manifest:
        raise ValueError("the manifest names at least one file")
    names = set()
    for f in manifest:
        name, digest = f.get("name"), f.get("sha256")
        if not isinstance(name, str) or not name or "\n" in name or "\r" in name or not _DIGEST.match(digest or ""):
            raise ValueError("each manifest entry is {name, sha256}: a name without line breaks and a 64-hex digest")
        if name in names:
            raise ValueError("%s is named twice" % name)
        names.add(name)
    body = "".join("%s %s\n" % (f["sha256"], f["name"]) for f in sorted(manifest, key=lambda f: f["name"].encode("utf-8")))
    return _sha256(MODEL_FORMAT + "\n" + body)


def model_digest(files, root=None):
    """The model digest of weight files, named by their path relative to root (default: the first file's folder)."""
    if not files:
        raise ValueError("name at least one weight file")
    base = os.path.abspath(root or os.path.dirname(os.path.abspath(files[0])))
    manifest = []
    for f in files:
        name = os.path.relpath(os.path.abspath(f), base).replace(os.sep, "/")
        if name.startswith(".."):
            raise ValueError("%s is not under %s" % (f, base))
        manifest.append({"name": name, "sha256": _file_sha256(f)})
    return model_digest_of_manifest(manifest)


def inference_nonce(model_digest_hex, input_digest_hex):
    """The nonce (frozen): SHA-256(UTF-8("riskrouter-inference-nonce|1|" + model_digest + "|" + input_digest))."""
    if not _DIGEST.match(model_digest_hex or "") or not _DIGEST.match(input_digest_hex or ""):
        raise ValueError("the model and input digests are 64 lowercase hex characters")
    return _sha256("%s|%s|%s" % (NONCE_FORMAT, model_digest_hex, input_digest_hex))


def inference_record(system_ref, model_digest, input, output, decoding, attestation=None, proof=None,
                     record_id=None, answered_at=None):
    """The ai.inference record for one call (pack ai-act). Only hashes are taken here."""
    if not _DIGEST.match(model_digest or ""):
        raise ValueError("model_digest is the 64-hex digest from model_digest()")
    if not system_ref or not decoding:
        raise ValueError("system_ref and decoding are required")
    when = answered_at or datetime.datetime.now(datetime.timezone.utc)
    input_digest = _sha256(input)
    record = {
        "pack": PACK, "pack_version": PACK_VERSION, "kind": KIND,
        "record_id": record_id or "inf-%s" % uuid.uuid4(),
        "system_ref": system_ref, "model_digest": model_digest,
        "input_digest": input_digest, "output_digest": _sha256(output),
        "decoding": str(decoding)[:200],
        "attestation_kind": attestation["kind"] if attestation else "none",
        "answered_at": when.astimezone(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    }
    if attestation:
        if attestation.get("kind") not in ATTESTATION_KINDS[1:]:
            raise ValueError("attestation kind is one of %s" % ", ".join(ATTESTATION_KINDS[1:]))
        if attestation.get("token") is None:
            raise ValueError("attestation token is the report or token exactly as the verifier returned it")
        record["attestation_nonce"] = inference_nonce(model_digest, input_digest)
        record["attestation_digest"] = _sha256(attestation["token"])
    if proof:
        if not proof.get("system") or proof.get("bytes") is None:
            raise ValueError("proof needs system and bytes")
        record["proof_system"] = str(proof["system"])[:80]
        record["proof_digest"] = _sha256(proof["bytes"])
    return record


def commit_inference(recorder, **call):
    """Commit a call through a Recorder; returns the record."""
    record = inference_record(**call)
    recorder.record(record, kind=KIND)
    return record


# ----------------------------------------------------- ECDSA on P-256 and P-384, verification only

_CURVES = {
    "P-256": dict(p=2**256 - 2**224 + 2**192 + 2**96 - 1,
                  b=0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B,
                  n=0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551,
                  g=(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,
                     0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5), size=32, hash=hashlib.sha256),
    "P-384": dict(p=2**384 - 2**128 - 2**96 + 2**32 - 1,
                  b=0xB3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF,
                  n=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973,
                  g=(0xAA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7,
                     0x3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F),
                  size=48, hash=hashlib.sha384),
}


def _ec_add(c, p1, p2):
    P = c["p"]
    if p1 is None:
        return p2
    if p2 is None:
        return p1
    if p1[0] == p2[0] and (p1[1] + p2[1]) % P == 0:
        return None
    if p1 == p2:
        lam = (3 * p1[0] * p1[0] - 3) * pow(2 * p1[1], -1, P) % P
    else:
        lam = (p2[1] - p1[1]) * pow(p2[0] - p1[0], -1, P) % P
    x3 = (lam * lam - p1[0] - p2[0]) % P
    return x3, (lam * (p1[0] - x3) - p1[1]) % P


def _ec_mul(c, k, pt):
    out = None
    while k:
        if k & 1:
            out = _ec_add(c, out, pt)
        pt = _ec_add(c, pt, pt)
        k >>= 1
    return out


def _b64url(s):
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))


def _ecdsa_verify(crv, x, y, message, sig):
    c = _CURVES[crv]
    P, n, size = c["p"], c["n"], c["size"]
    q = (x, y)
    if not (0 <= x < P and 0 <= y < P) or (y * y - (x ** 3 - 3 * x + c["b"])) % P:
        return False
    if len(sig) != 2 * size:
        return False
    r, s = int.from_bytes(sig[:size], "big"), int.from_bytes(sig[size:], "big")
    if not (0 < r < n and 0 < s < n):
        return False
    e = int.from_bytes(c["hash"](message).digest(), "big")
    w = pow(s, -1, n)
    pt = _ec_add(c, _ec_mul(c, e * w % n, c["g"]), _ec_mul(c, r * w % n, q))
    return pt is not None and pt[0] % n == r


def _nras_parts(token):
    """A JWT is itself; NRAS answers [["JWT", overall], {gpu: token}]: the overall token and the per-GPU tokens."""
    text = token.decode("utf-8", "replace") if isinstance(token, (bytes, bytearray)) else str(token)
    text = text.strip()
    if not text.startswith("["):
        return text, []
    try:
        doc = json.loads(text)
        overall = str(doc[0][1]) if isinstance(doc[0], list) else str(doc[0])
        gpus = [(k, str(v)) for k, v in doc[1].items()] if len(doc) > 1 and isinstance(doc[1], dict) else []
        return overall, gpus
    except Exception:
        return text, []


def verify_jwt(jwt, jwks):
    """(True, kid, claims) when a key of the key set signed the JWT (ES256 or ES384); else (False, reason, None)."""
    parts = str(jwt).strip().split(".")
    if len(parts) != 3:
        return False, "not a JWT", None
    try:
        header, claims = json.loads(_b64url(parts[0])), json.loads(_b64url(parts[1]))
    except Exception:
        return False, "the JWT's header or claims are not JSON", None
    want = {"ES256": "P-256", "ES384": "P-384"}.get(header.get("alg"))
    if not want:
        return False, "algorithm %s is not accepted (ES256 or ES384 only)" % header.get("alg"), None
    keys = [k for k in (jwks or {}).get("keys", []) if k.get("kty") == "EC" and k.get("crv") == want
            and (not header.get("kid") or k.get("kid") == header.get("kid"))]
    if not keys:
        return False, "no key %sin the key set" % ("with kid %s " % header["kid"] if header.get("kid") else ""), None
    message = ("%s.%s" % (parts[0], parts[1])).encode("ascii")
    sig = _b64url(parts[2])
    for k in keys:
        x, y = int.from_bytes(_b64url(k["x"]), "big"), int.from_bytes(_b64url(k["y"]), "big")
        if _ecdsa_verify(want, x, y, message, sig):
            return True, k.get("kid"), claims
    return False, "the signature does not verify against the key set", None


def eat_nonce(token):
    """The nonces an EAT (RFC 9711) token in JWT form carries, or None. Its signature is not checked here."""
    token = _nras_parts(token)[0]
    parts = str(token).strip().split(".")
    if len(parts) != 3:
        return None
    try:
        claims = json.loads(base64.urlsafe_b64decode(parts[1] + "=" * (-len(parts[1]) % 4)))
    except Exception:
        return None
    n = claims.get("eat_nonce") if isinstance(claims, dict) else None
    if n is None:
        return None
    return [str(x) for x in n] if isinstance(n, list) else [str(n)]


def check_inference(record, input=None, output=None, model_digest=None, attestation_token=None, jwks=None, proof_bytes=None, now=None):
    """Lines of ("ok" | "failed" | "skipped", text), like the verifiers'."""
    out = []

    def same(what, want, got):
        out.append(("ok", "%s matches the record" % what) if want == got else ("failed", "%s does not match the record" % what))

    if not isinstance(record, dict) or record.get("kind") != KIND:
        return [("failed", "not an %s record" % KIND)]
    if input is not None:
        same("input", record.get("input_digest"), _sha256(input))
    else:
        out.append(("skipped", "input: not shown"))
    if output is not None:
        same("output", record.get("output_digest"), _sha256(output))
    else:
        out.append(("skipped", "output: not shown"))
    if model_digest is not None:
        same("model", record.get("model_digest"), model_digest)
    else:
        out.append(("skipped", "model: not shown"))
    if record.get("attestation_digest"):
        nonce = inference_nonce(record["model_digest"], record["input_digest"])
        out.append(("ok", "attestation nonce: derived from this model and input") if record.get("attestation_nonce") == nonce
                   else ("failed", "attestation nonce: not the one this model and input give"))
        if attestation_token is not None:
            same("attestation token", record["attestation_digest"], _sha256(attestation_token))
            carried = eat_nonce(attestation_token)
            if carried:
                out.append(("ok", "attestation: the token carries this call's nonce (eat_nonce)") if nonce in carried
                           else ("failed", "attestation: the token was issued for another nonce"))
            else:
                out.append(("skipped", "attestation: not an EAT token in JWT form; check its nonce with the vendor's tools"))
            if jwks:
                overall, gpus = _nras_parts(attestation_token)
                ok, kid, claims = verify_jwt(overall, jwks)
                if not ok:
                    out.append(("failed", "attestation signature: %s" % kid))
                else:
                    out.append(("ok", "attestation signature: verifies against key %s of the key set you supplied" % (kid or "(no kid)")))
                    result = claims.get("x-nvidia-overall-att-result")
                    if result is True:
                        out.append(("ok", "attestation: the vendor's overall result is a pass (x-nvidia-overall-att-result)"))
                    elif result is False:
                        out.append(("failed", "attestation: the vendor's overall result is a failure (x-nvidia-overall-att-result)"))
                    for gid, t in gpus:
                        g = verify_jwt(t, jwks)
                        out.append(("ok", "attestation: the token for %s verifies too" % gid) if g[0]
                                   else ("failed", "attestation: the token for %s: %s" % (gid, g[1])))
                out.append(("skipped", "attestation: the key set is yours to have taken from the vendor; whether the hardware itself is honest rests on the vendor's keys"))
            else:
                out.append(("skipped", "attestation signature: pass the vendor's key set (jwks) to check it here, or use the vendor's verifier"))
        else:
            out.append(("skipped", "attestation token: not shown"))
    if record.get("proof_digest"):
        if proof_bytes is not None:
            same("proof file", record["proof_digest"], _sha256(proof_bytes))
        else:
            out.append(("skipped", "proof file: not shown"))
        out.append(("skipped", "proof: check it with %s's own verifier" % (record.get("proof_system") or "its proof system")))
    return out
