"""ML-DSA-65 cryptographic operations for Electrum-BTCQ."""
from pqcrypto.sign.ml_dsa_65 import (
    generate_keypair as _generate_keypair,
    sign as _sign,
    verify as _verify,
)
from electrum.mldsa_keygen import mldsa_keygen_from_seed as _keygen_from_seed


def mldsa_generate_keypair():
    """Random ML-DSA-65 keypair. Returns (pk: 1952B, sk: 4032B)."""
    return _generate_keypair()


def mldsa_keygen_from_seed(xi: bytes):
    """Deterministic keygen from 32-byte seed. Returns (pk, sk)."""
    return _keygen_from_seed(xi)


def mldsa_sign(secret_key: bytes, message: bytes) -> bytes:
    """Sign. Returns 3309-byte signature."""
    return _sign(secret_key, message)


def mldsa_verify(public_key: bytes, message: bytes, signature: bytes) -> bool:
    """Verify. Returns True if valid."""
    try:
        result = _verify(public_key, message, signature)
        # pqcrypto may return bool or raise on failure
        if result is False:
            return False
        return True
    except Exception:
        return False
