"""Offline private read/reply receipt verification. Requires cryptography."""
import argparse
import base64
import hashlib
import json
import re
import sys
from pathlib import Path

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


def require(condition, message):
    if not condition:
        raise ValueError(message)


def unique(pairs):
    result = {}
    for key, value in pairs:
        require(key not in result, "duplicate JSON key")
        result[key] = value
    return result


def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode()


def verify(path, key, pin):
    record = json.loads(path.read_bytes(), object_pairs_hook=unique)
    sig, integrity = record["signature"], record["integrity"]
    manifest = sig["manifest"]
    require(manifest["schema_version"] == "haltstate.inline-proof-export.v1" and
            record["schema_version"] == "haltstate.private-read-reply.v1", "unexpected receipt format")
    require(sig["algorithm"] == "Ed25519" and manifest["signer"]["public_key_fingerprint"] == pin,
            "unexpected signer")
    key.verify(base64.b64decode(sig["value"], validate=True),
               b"HALTSTATE-EVIDENCE-EXPORT-MANIFEST-v1\x00" + canonical(manifest))
    body = {k: v for k, v in record.items() if k not in {"signature", "integrity"}}
    digest = hashlib.sha256(canonical(body)).hexdigest()
    require(manifest["payload_sha256"] == integrity["hash"] == digest and
            sig["hash"] == "sha256:" + digest, "content digest mismatch")
    require(manifest["tenant_id"] == record["tenant_id"] and
            manifest["export_id"] == record["export_id"] == record["receipt_id"] and
            sig["signing_key_id"] == manifest["signer"]["key_id"] and
            integrity["signed_at"] == sig["signed_at"] == record["generated_at"] and
            integrity["algorithm"] == "SHA-256" and integrity["evidence_mode"] == "signed",
            "inconsistent receipt envelope")
    return body, digest


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("public_pem", type=Path)
    parser.add_argument("raw_key_sha256", help="Independently trusted SHA-256 fingerprint")
    parser.add_argument("read_json", type=Path)
    parser.add_argument("reply_json", type=Path, nargs="?")
    parser.add_argument("--reply-bytes", type=Path, help="Also compare with the exact prepared body")
    args = parser.parse_args()
    key = serialization.load_pem_public_key(args.public_pem.read_bytes())
    require(isinstance(key, Ed25519PublicKey), "expected Ed25519 key")
    raw = key.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
    require(hashlib.sha256(raw).hexdigest() == args.raw_key_sha256, "untrusted public key")
    read, parent_hash = verify(args.read_json, key, args.raw_key_sha256)
    require(read["phase"] == "read" and read["decision"] in {"ALLOW", "DENY"}, "expected read decision")
    if args.reply_json:
        reply, _ = verify(args.reply_json, key, args.raw_key_sha256)
        require(read["decision"] == "ALLOW" and reply["decision"] == "ALLOW" and reply["phase"] == "reply",
                "expected an authorized read and reply pair")
        require(reply["read_receipt_id"] == read["receipt_id"] and reply["read_payload_sha256"] == parent_hash
                and read["receipt_id"] != reply["receipt_id"] and
                all(read[k] == reply[k] for k in ("tenant_id", "agent_id", "resource_binding_sha256")),
                "receipts do not belong to the same read and reply")
        require(re.fullmatch("[0-9a-f]{64}", reply["reply_sha256"]), "invalid reply digest")
        if args.reply_bytes:
            require(hashlib.sha256(args.reply_bytes.read_bytes()).hexdigest() == reply["reply_sha256"],
                    "prepared reply bytes differ")
        print("Verified: two signed ALLOW decisions, linked to the same private read.")
    else:
        require(not args.reply_bytes, "provide the reply receipt to verify its bytes")
        print("Verified signed read decision:", read["decision"])


if __name__ == "__main__":
    try:
        main()
    except (ValueError, TypeError, KeyError, OSError, InvalidSignature) as exc:
        sys.exit("Verification failed: " + (str(exc) or "invalid signature"))
