#!/usr/bin/env python3
"""Verify the signed core of a typed LA4KB V3 receipt against its request.

Usage:
    python tools/verify_v3_receipt.py request.json receipt.json pubkey.json

The public key file is the saved JSON response from GET /api/v3/pubkey.
This build-specific verifier pins that endpoint's public key and manifest
identity. Requires Python 3.12.10 and ``cryptography``. It does not assert
that unsigned lifecycle metadata or the declared evidence is true.
"""

from __future__ import annotations

import hashlib
import hmac
import json
import math
import sys
import unicodedata
from decimal import Decimal
from pathlib import Path
from typing import Any

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey


CONTRACT_VERSION = "la4kb-v3-typed-candidate-1"
BINDING_VERSION = "la4kb-payload-result-binding-v1"
DOMAIN_PREFIX = b"LA4KB-PAYLOAD-RESULT-BINDING-V1\x1f"
PINNED_BUILD = "v3t-1013d7ecf712"
PINNED_SCHEMA_VERSION = "la4kb-public-api-v3-typed-candidate-1"
PINNED_MANIFEST_SHA256 = "b54f293d40f263dce4da055ec750e87683bf1e559d340de953452c5c80a17c7a"
PINNED_PUBLIC_KEY_HEX = "de8b53138bfe735d65a9842f6d695feb663f194c7f67de4a07df859b092ba252"
PINNED_PYTHON_VERSION = (3, 12, 10)
PINNED_UNICODE_VERSION = "15.0.0"
ROOT_FIELDS = frozenset(
    {
        "contract_version",
        "scope_schema_id",
        "client_reference",
        "claim",
        "evidence_items",
        "provenance",
        "origin_category",
        "researcher_attribution",
    }
)
PROVENANCE_FIELDS = (
    "declared_origin",
    "agent_name",
    "model_declared",
    "researcher_handle",
    "notes",
    "campaign_id",
)
UNSIGNED_RECEIPT_METADATA_EXAMPLES = (
    "origin_category",
    "entry_surface",
    "status",
    "error_code",
    "entry_surface_basis",
    "queue_age_ms",
    "processing_age_ms",
    "researcher_metadata",
    "created_at",
    "started_at",
    "finished_at",
)
VERDICTS = frozenset(
    {
        "SUPPORTED",
        "CONTRADICTED",
        "CONFLICTED",
        "INSUFFICIENT_EVIDENCE",
        "NOT_COMPARABLE",
        "SUPPORTED_WITH_SCOPE",
    }
)


def _unique_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
    result: dict[str, Any] = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"duplicate JSON key: {key}")
        result[key] = value
    return result


def _invalid_constant(value: str) -> None:
    raise ValueError(f"non-finite JSON number: {value}")


def _exact_json_float(literal: str) -> float:
    value = float(literal)
    if not math.isfinite(value) or Decimal(literal) != Decimal(repr(value)):
        raise ValueError("JSON decimal loses precision under V3 admission")
    return value


def _load_json(path: str) -> dict[str, Any]:
    data = json.loads(
        Path(path).read_text(encoding="utf-8"),
        object_pairs_hook=_unique_pairs,
        parse_float=_exact_json_float,
        parse_constant=_invalid_constant,
    )
    if not isinstance(data, dict):
        raise ValueError(f"{path}: expected a JSON object")
    return data


def _canonical_json(value: Any) -> bytes:
    # The production V3 hash uses Python json.dumps on Pydantic model_dump().
    return json.dumps(
        value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False
    ).encode("utf-8")


def canonical_v3_payload(request: dict[str, Any]) -> dict[str, Any]:
    """Reproduce ChallengeRequestV3Typed.model_dump() for an admitted request.

    The typed claim and evidence are dict fields in that model; validation does
    not normalize their declared values. The root and ProvenanceInput defaults
    below are the fields Pydantic adds when the sender omits them.
    """
    if request.get("contract_version") != CONTRACT_VERSION:
        raise ValueError("unsupported V3 contract_version")
    if not isinstance(request.get("scope_schema_id"), str):
        raise ValueError("scope_schema_id is required")
    if not isinstance(request.get("claim"), dict):
        raise ValueError("claim must be an object")
    if not isinstance(request.get("evidence_items", []), list):
        raise ValueError("evidence_items must be an array")
    unknown = request.keys() - ROOT_FIELDS
    if unknown:
        raise ValueError(f"unknown root fields: {sorted(unknown)}")

    normalized = {
        "contract_version": request["contract_version"],
        "scope_schema_id": request["scope_schema_id"],
        "client_reference": request.get("client_reference"),
        "claim": request["claim"],
        "evidence_items": request.get("evidence_items", []),
        "provenance": None,
        "origin_category": request.get("origin_category"),
        "researcher_attribution": request.get("researcher_attribution"),
    }
    provenance = request.get("provenance")
    if provenance is not None:
        if not isinstance(provenance, dict):
            raise ValueError("provenance must be an object or null")
        unknown = provenance.keys() - set(PROVENANCE_FIELDS)
        if unknown:
            raise ValueError(f"unknown provenance fields: {sorted(unknown)}")
        normalized["provenance"] = {
            field: provenance.get(field) for field in PROVENANCE_FIELDS
        }
    return normalized


def _sha256(value: bytes) -> str:
    return hashlib.sha256(value).hexdigest()


def _assert_runtime() -> None:
    if sys.version_info[:3] != PINNED_PYTHON_VERSION or unicodedata.unidata_version != PINNED_UNICODE_VERSION:
        raise ValueError("this V3 verifier requires Python 3.12.10 with Unicode 15.0.0")


def _signature_bytes(value: Any) -> bytes:
    if not isinstance(value, str) or not value.startswith("ed25519:"):
        raise ValueError("expected ed25519:<hex> signature")
    raw = bytes.fromhex(value.split(":", 1)[1])
    if len(raw) != 64:
        raise ValueError("Ed25519 signature must be 64 bytes")
    return raw


def _verify_signature(key: Ed25519PublicKey, signature: Any, message: bytes) -> None:
    try:
        key.verify(_signature_bytes(signature), message)
    except InvalidSignature as exc:
        raise ValueError("invalid Ed25519 signature") from exc


def verify(request: dict[str, Any], receipt: dict[str, Any], pubkey: dict[str, Any]) -> dict[str, Any]:
    _assert_runtime()
    key_hex = pubkey.get("public_key_hex")
    if not isinstance(key_hex, str) or not hmac.compare_digest(key_hex, PINNED_PUBLIC_KEY_HEX):
        raise ValueError("public key does not match the pinned V3 build key")
    if pubkey.get("algorithm") != "ed25519":
        raise ValueError("public key algorithm is not Ed25519")
    if pubkey.get("schema_version") != PINNED_SCHEMA_VERSION:
        raise ValueError("public key schema does not match this verifier")
    if pubkey.get("scope_manifest_sha256") != PINNED_MANIFEST_SHA256:
        raise ValueError("public key manifest does not match this verifier")
    if pubkey.get("payload_result_binding_version") != BINDING_VERSION:
        raise ValueError("public key binding version does not match this verifier")
    key = Ed25519PublicKey.from_public_bytes(bytes.fromhex(key_hex))
    build = receipt.get("engine_build")
    if build != PINNED_BUILD or pubkey.get("engine_build") != PINNED_BUILD:
        raise ValueError("receipt or public-key build does not match the pinned V3 build")
    job_id = receipt.get("job_id")
    if not isinstance(job_id, str) or not job_id:
        raise ValueError("receipt needs job_id")
    if receipt.get("binding_version") != BINDING_VERSION:
        raise ValueError("unsupported or absent payload-result binding")

    normalized_request = canonical_v3_payload(request)
    request_reference = normalized_request["client_reference"]
    if request_reference is not None and not isinstance(request_reference, str):
        raise ValueError("request client_reference must be a string or null")
    if "client_reference" not in receipt:
        raise ValueError("receipt client_reference is absent")
    receipt_reference = receipt["client_reference"]
    if receipt_reference is not None and not isinstance(receipt_reference, str):
        raise ValueError("receipt client_reference must be a string or null")
    if type(receipt_reference) is not type(request_reference) or receipt_reference != request_reference:
        raise ValueError("receipt client_reference does not match the supplied V3 request")
    verdict = receipt.get("verdict")
    if not isinstance(verdict, str) or verdict not in VERDICTS:
        raise ValueError("receipt verdict must be a completed V3 verdict")

    request_hash = _sha256(_canonical_json(normalized_request))
    declared_hash = receipt.get("payload_hash")
    if not isinstance(declared_hash, str) or not hmac.compare_digest(request_hash, declared_hash):
        raise ValueError("receipt payload_hash does not match the supplied V3 request")

    result = {
        "client_reference": receipt_reference or "",
        "engine_build": build,
        "job_id": job_id,
        "verdict": verdict,
    }
    result_hash = _sha256(_canonical_json(result))
    declared_result_hash = receipt.get("result_hash")
    if not isinstance(declared_result_hash, str) or not hmac.compare_digest(result_hash, declared_result_hash):
        raise ValueError("receipt result_hash does not match the visible result")
    _verify_signature(
        key, receipt.get("signature"), f"{build}:{job_id}:{result_hash}".encode("utf-8")
    )

    binding = {
        "version": BINDING_VERSION,
        "payload_hash": request_hash,
        "result_hash": result_hash,
        "engine_build": build,
        "job_id": job_id,
    }
    _verify_signature(
        key,
        receipt.get("binding_signature"),
        DOMAIN_PREFIX + _canonical_json(binding),
    )
    return {
        "signed_core_verified": True,
        "request_hash_recomputed": True,
        "public_key_pinned": True,
        "engine_build": build,
        "job_id": job_id,
        "verdict": verdict,
        "payload_hash": request_hash,
        "result_hash": result_hash,
        "unsigned_receipt_metadata_examples": list(UNSIGNED_RECEIPT_METADATA_EXAMPLES),
    }


def main(argv: list[str]) -> int:
    if len(argv) != 4:
        print("usage: verify_v3_receipt.py request.json receipt.json pubkey.json", file=sys.stderr)
        return 2
    try:
        result = verify(_load_json(argv[1]), _load_json(argv[2]), _load_json(argv[3]))
    except (OSError, ValueError, TypeError, KeyError) as exc:
        print(f"VERIFICATION FAILED: {exc}", file=sys.stderr)
        return 1
    print(json.dumps(result, sort_keys=True, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
