"""Extrae wallets BTC y ETH de un texto, con offsets."""

import re

_BTC_LEGACY = re.compile(
    r"(?<![A-Za-z0-9])"
    r"[13][1-9A-HJ-NP-Za-km-z]{25,34}"
    r"(?![A-Za-z0-9])"
)
_BTC_BECH32 = re.compile(
    r"(?<![A-Za-z0-9])"
    r"bc1[02-9ac-hj-np-z]{6,87}"
    r"(?![A-Za-z0-9])"
)
_ETH_REGEX = re.compile(
    r"(?<![A-Za-z0-9])"
    r"0x[a-fA-F0-9]{40}"
    r"(?![A-Za-z0-9])"
)


def extract_crypto_wallets(text: str) -> list[dict]:
    """Extrae direcciones BTC (legacy + bech32) y ETH con offsets.

    BTC legacy (P2PKH/P2SH) empieza por `1` o `3`. BTC bech32 (segwit)
    empieza por `bc1`. ETH es `0x` seguido de 40 caracteres hex. No se
    valida checksum — la regex es estructural.
    """
    results = []
    for regex, asset in (
        (_BTC_LEGACY, "btc"),
        (_BTC_BECH32, "btc"),
        (_ETH_REGEX, "eth"),
    ):
        for m in regex.finditer(text):
            results.append({
                "value": m.group(0),
                "start": m.start(),
                "end": m.end(),
                "type": "crypto_wallet",
                "asset": asset,
            })
    results.sort(key=lambda r: r["start"])
    return results
