"""Tests for electrum.btcq_addr — BTCQ address encoding/decoding."""
import importlib.util
import os
import sys

_ELECTRUM_DIR = os.path.join(os.path.dirname(__file__), '..', 'electrum')

def _load(name, filename):
    spec = importlib.util.spec_from_file_location(name, os.path.join(_ELECTRUM_DIR, filename))
    mod = importlib.util.module_from_spec(spec)
    sys.modules[name] = mod
    spec.loader.exec_module(mod)
    return mod

# Load in dependency order
_load('electrum.mldsa_keygen', 'mldsa_keygen.py')
mldsa = _load('electrum.mldsa', 'mldsa.py')
btcq_crypto = _load('electrum.btcq_crypto', 'btcq_crypto.py')
_load('electrum.segwit_addr', 'segwit_addr.py')
btcq_addr = _load('electrum.btcq_addr', 'btcq_addr.py')


def _dummy_pubkey():
    pk, _ = mldsa.mldsa_keygen_from_seed(b'\x00' * 32)
    return pk


def test_pubkey_to_address_regtest_prefix():
    pk = _dummy_pubkey()
    addr = btcq_addr.pubkey_to_address(pk, 'regtest')
    assert addr.startswith('btcqrt1'), f"regtest addr should start with btcqrt1, got {addr}"


def test_pubkey_to_address_mainnet_prefix():
    pk = _dummy_pubkey()
    addr = btcq_addr.pubkey_to_address(pk, 'mainnet')
    assert addr.startswith('btcq1'), f"mainnet addr should start with btcq1, got {addr}"


def test_pubkey_to_address_testnet_prefix():
    pk = _dummy_pubkey()
    addr = btcq_addr.pubkey_to_address(pk, 'testnet')
    assert addr.startswith('btcqt1'), f"testnet addr should start with btcqt1, got {addr}"


def test_is_btcq_address():
    pk = _dummy_pubkey()
    for net in ('mainnet', 'testnet', 'regtest'):
        addr = btcq_addr.pubkey_to_address(pk, net)
        assert btcq_addr.is_btcq_address(addr), f"{net} address not recognized"
    assert not btcq_addr.is_btcq_address("bc1qfoobar")
    assert not btcq_addr.is_btcq_address("1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa")


def test_roundtrip_address_to_script():
    pk = _dummy_pubkey()
    addr = btcq_addr.pubkey_to_address(pk, 'regtest')
    script = btcq_addr.address_to_script(addr)
    # P2WPKH: OP_0 <20-byte-hash>
    assert script[0] == 0x00
    assert script[1] == 20
    assert len(script) == 22


def test_address_to_scripthash():
    script = bytes([0x00, 0x14] + list(range(20)))
    sh = btcq_addr.address_to_scripthash(script)
    expected = btcq_crypto.sha3_256(script).hex()
    assert sh == expected
    assert len(sh) == 64


def test_address_to_script_invalid():
    try:
        btcq_addr.address_to_script("bc1qinvalid")
        assert False, "should have raised ValueError"
    except ValueError:
        pass


if __name__ == "__main__":
    tests = [f for f in dir() if f.startswith('test_')]
    for t in sorted(tests):
        print(f"  {t} ... ", end="", flush=True)
        globals()[t]()
        print("OK")
    print(f"\nAll {len(tests)} btcq_addr tests passed.")
