#!/usr/bin/env python3
"""Verify a ThePlus Control Plane evidence export with its public key alone.

    python3 scripts/verify_evidence_export.py export.json evidence_public_key.pem

For an auditor: this file does not import the Control Plane and needs only the
`cryptography` package. It cannot sign anything, so a passing result means the
holder of the private key produced exactly this payload.

Obtain the public key out of band (for example, sent to you directly and
compared by key id), not from the export itself: an attacker who rewrote an
export could also attach their own key. The script checks that the export names
the key you trust.

Exit 0 = VERIFIED. Exit 1 = NOT VERIFIED, with the reason.
"""

from __future__ import annotations

import base64
import hashlib
import json
import sys
from pathlib import Path

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

SUPPORTED_FORMAT = "theplus-signed-export/2"


def canonical_json(value) -> bytes:
    # Must stay byte-identical to app/core/canonical.canonical_json (a test pins the two together).
    return json.dumps(value, sort_keys=True, separators=(",", ":"), default=str).encode()


def key_id(public_key: Ed25519PublicKey) -> str:
    raw = public_key.public_bytes(encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw)
    return "ed25519:" + base64.urlsafe_b64encode(raw[:12]).decode().rstrip("=")


def verify(export: dict, public_key_pem: bytes) -> tuple[bool, str]:
    if not isinstance(export, dict) or export.get("format") != SUPPORTED_FORMAT:
        found = export.get("format") if isinstance(export, dict) else type(export).__name__
        return False, f"unsupported export format {found!r} (this verifier reads {SUPPORTED_FORMAT})"
    payload, sig = export.get("payload"), export.get("public_signature")
    if not isinstance(payload, dict) or not isinstance(sig, dict) or sig.get("algorithm") != "Ed25519":
        return False, "malformed export: payload or Ed25519 signature missing"
    try:
        key = serialization.load_pem_public_key(public_key_pem)
    except ValueError:
        return False, "the public key file is not a readable PEM key"
    if not isinstance(key, Ed25519PublicKey):
        return False, "the public key is not an Ed25519 key"
    trusted = key_id(key)
    if sig.get("key_id") != trusted:
        return False, f"the export is signed by key {sig.get('key_id')!r}, not the trusted key {trusted!r}"
    body = canonical_json(payload)
    if sig.get("payload_hash") != "sha256:" + hashlib.sha256(body).hexdigest():
        return False, "the payload does not match its recorded hash: it was altered after signing"
    try:
        key.verify(base64.urlsafe_b64decode(str(sig.get("value", "")).encode()), body)
    except Exception:  # noqa: BLE001 — any failure is a failed verification
        return False, "the Ed25519 signature does not verify"

    def count(key):
        items = payload.get(key)
        return len(items) if isinstance(items, list) else 0

    cut = [k for k, v in (payload.get("completeness") or {}).items() if isinstance(v, dict) and v.get("truncated")]
    note = f" (TRUNCATED by the exporter: {', '.join(cut)}; see completeness)" if cut else ""
    return (
        True,
        f"VERIFIED: signed by {trusted}; {count('decisions')} decisions, {count('acn_acknowledgements')} ACN acknowledgements{note}",
    )


def _no_duplicate_keys(pairs):
    seen, dupes = set(), set()
    for k, _ in pairs:  # one pass: keys.count() per key was quadratic
        (dupes if k in seen else seen).add(k)
    if dupes:
        # Two parsers could read different values from one file; refuse it instead of picking one.
        raise ValueError(f"duplicate JSON keys {sorted(dupes)}: the export is ambiguous")
    return dict(pairs)


def _refuse_constant(name):
    raise ValueError(f"non-standard JSON number {name}: strict JSON has no NaN or Infinity")


def load_export(text: str):
    return json.loads(text, object_pairs_hook=_no_duplicate_keys, parse_constant=_refuse_constant)


def main(argv: list[str]) -> int:
    if len(argv) != 3:
        print(__doc__.strip().splitlines()[2].strip())
        return 2
    try:
        export = load_export(Path(argv[1]).read_text(encoding="utf-8"))
    except (OSError, ValueError, RecursionError) as exc:
        print(f"NOT VERIFIED: cannot read the export: {exc}")
        return 1
    try:
        pem = Path(argv[2]).read_bytes()
    except OSError as exc:
        print(f"NOT VERIFIED: cannot read the public key: {exc}")
        return 1
    try:
        ok, reason = verify(export, pem)
    except RecursionError:
        ok, reason = False, "the export is nested too deeply to check"
    print(reason if ok else f"NOT VERIFIED: {reason}")
    return 0 if ok else 1


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