#!/usr/bin/env python3
"""Verify downloaded proof bytes and a Solve Open Problems checker receipt."""
import argparse
import base64
import hashlib
import json
from pathlib import Path
import subprocess
import tempfile


def verify(receipt_path, proof, public_key):
    receipt = json.loads(receipt_path.read_bytes())
    if receipt["algorithm"] != "Ed25519":
        raise ValueError("Unsupported signature algorithm.")
    key = subprocess.run(
        ["openssl", "pkey", "-pubin", "-in", str(public_key), "-outform", "DER"],
        check=True, capture_output=True,
    ).stdout
    if hashlib.sha256(key).hexdigest() != receipt["keyId"]:
        raise ValueError("The supplied public key does not match the receipt.")
    payload = receipt["payload"].encode("utf-8")
    with tempfile.TemporaryDirectory() as directory:
        message = Path(directory) / "payload"
        signature = Path(directory) / "signature"
        message.write_bytes(payload)
        signature.write_bytes(base64.b64decode(receipt["signature"], validate=True))
        subprocess.run(
            ["openssl", "pkeyutl", "-verify", "-rawin", "-pubin", "-inkey", str(public_key),
             "-in", str(message), "-sigfile", str(signature)],
            check=True, capture_output=True,
        )
    verdict = json.loads(payload)
    if verdict["type"] != "solveopenproblems.lean-verdict.v1" or verdict["verdict"] != "accepted":
        raise ValueError("Unrecognized checker verdict.")
    axioms = verdict["axioms"]
    if not isinstance(axioms, list) or any(item not in ("propext", "Classical.choice", "Quot.sound") for item in axioms):
        raise ValueError("The receipt contains an unsupported axiom.")
    if hashlib.sha256(proof.read_bytes()).hexdigest() != verdict["sourceSha256"]:
        raise ValueError("The downloaded Lean bytes do not match the signed verdict.")
    return verdict


if __name__ == "__main__":
    args = argparse.ArgumentParser(description=__doc__)
    args.add_argument("receipt", type=Path)
    args.add_argument("proof", type=Path)
    args.add_argument("public_key", type=Path)
    files = args.parse_args()
    try:
        print(json.dumps(verify(files.receipt, files.proof, files.public_key), indent=2))
    except subprocess.CalledProcessError as error:
        detail = (error.stderr or b"").decode("utf-8", "replace").strip()
        args.exit(1, f"OpenSSL could not verify the receipt. {detail or error}\n")
    except (AttributeError, KeyError, ValueError, TypeError, OSError) as error:
        args.exit(1, f"Receipt verification failed. {error}\n")
