"""BTCQ address encoding/decoding."""
from electrum.btcq_crypto import hash_160_btcq, sha3_256
from electrum.segwit_addr import encode_segwit_address, decode_segwit_address

BTCQ_HRPS = {'mainnet': 'btcq', 'testnet': 'btcqt', 'regtest': 'btcqrt'}


def pubkey_to_address(pubkey: bytes, net_type: str = 'regtest') -> str:
    """ML-DSA-65 pubkey -> bech32 P2WPKH address."""
    h160 = hash_160_btcq(pubkey)
    return encode_segwit_address(BTCQ_HRPS[net_type], 0, h160)


def address_to_scripthash(script: bytes) -> str:
    """Electrum protocol scripthash: SHA3-256, natural byte order."""
    return sha3_256(script).hex()


def is_btcq_address(addr: str) -> bool:
    for hrp in BTCQ_HRPS.values():
        if addr.lower().startswith(hrp + '1'):
            return True
    return False


def address_to_script(addr: str) -> bytes:
    """Decode a BTCQ address to its scriptPubKey."""
    for net, hrp in BTCQ_HRPS.items():
        if addr.lower().startswith(hrp + '1'):
            witver, witprog = decode_segwit_address(hrp, addr)
            if witver is not None:
                script = bytes([0x00, len(witprog)] + list(witprog))
                return script
    raise ValueError(f"unrecognized BTCQ address: {addr}")
