# -*- coding: utf-8 -*-
"""TrendAI — universo de moedas (SEMPRE pares spot USDT — decisão do usuário).

Filtra a Binance spot: quote USDT, status TRADING, exclui bases fiat/stable,
tokens alavancados (sufixo UP/DOWN), notional 24h mínimo e listagens recentes.
Cache de klines em SQLite (data/trendai_aprendizado.db).
"""
import time

from trendai_api_uso import registrar
from trendai_banco import conectar, klines_cache_gravar, klines_cache_ler
from trendai_conexao import carregar_config, exchange_mercado

# Idade máxima do cache por timeframe (s) — ciclo roda a cada 4h
_CACHE_IDADE = {'1h': 3600.0, '4h': 7200.0, '1d': 14400.0}


# Moedas bloqueadas para usuários do Brasil na Binance (restrição regulatória
# local — não dá para comprar/vender por conta BR). Lista FIXA no engine:
# independe do config e não se perde num salvamento pela página Configurações.
# Complementa universo.excluir_bases (config editável).
#   - OM = ticker do Mantra (o usuário listou "MANTRA" pelo nome);
#   - USDE/USTC = stablecoins algorítmicas/sintéticas.
_BLOQUEADAS_BR = {
    'USDE', 'USTC',
    'DCR', 'DUSK', 'PIVX', 'SCRT', 'XVG',
    'ACX', 'BB', 'GMT', 'HIT', 'ICX', 'MANTRA', 'OM', 'ONE', 'ONT', 'PYR',
    'RVN', 'STORJ', 'TFUEL', 'VANRY', 'VIC', 'ZIL',
}


# Stablecoins/fiats com ticker "não óbvio" (a regra genérica só pega bases que
# terminam em USD/USDT). Caso real: "U" (United Stables) liderou o ranking por
# 69 ciclos — peg a US$ 1,00 = risco/vol. perfeitos + RS positiva nas quedas do
# BTC — e contaminou o aprendizado (EV e pesos de fatores). Lista FIXA no engine
# (não se perde no salvamento do config) + detecção automática de peg abaixo.
STABLES_FIXAS = {
    'U', 'USDC', 'FDUSD', 'TUSD', 'DAI', 'USDP', 'USDE', 'USD1', 'USDS', 'USDG',
    'USDD', 'USTC', 'XUSD', 'SUSD', 'VAI', 'PAX',
    'EUR', 'EURI', 'EURC', 'EURQ', 'AEUR', 'GBP', 'AUD', 'BRL', 'TRY', 'RUB',
    'UAH', 'NGN', 'BIDR', 'IDRT', 'BKRW',
}
BLOQUEADAS_BR = _BLOQUEADAS_BR


def e_stablecoin(base):
    """True p/ stablecoin/fiat: lista fixa + regra genérica (sufixo USD/USDT).
    Usada no universo E no aprendizado (apostas de stables não ensinam nada)."""
    b = str(base or '').upper()
    return b in STABLES_FIXAS or b.endswith('USD') or b.endswith('USDT')


def _e_alavancado(base):
    b = base.upper()
    return b.endswith('UP') or b.endswith('DOWN') or b.endswith('BULL') or b.endswith('BEAR')


def _e_stable_ou_fiat(base, excluir):
    """Stablecoins/fiats: lista de exclusão + regra genérica (tickers reais não
    terminam em 'USD' — pega RLUSD, BFUSD, FDUSD, PYUSD, USDS etc. que vazaram
    na validação de 02/11/2026, quando RLUSD entrou no ranking)."""
    b = base.upper()
    return b in excluir or b.endswith('USD') or b.endswith('USDT')


def listar_universo(exchange=None, log=None):
    """Retorna lista de dicts {'symbol', 'base', 'notional', 'var24h'} dos pares
    spot USDT elegíveis, ordenada por notional decrescente."""
    cfg = carregar_config().get('universo', {})
    quote = cfg.get('quote', 'USDT')
    notional_min = float(cfg.get('notional_min_24h', 1_000_000))
    idade_min_dias = float(cfg.get('idade_min_dias', 30))
    max_moedas = int(cfg.get('max_moedas', 400))
    excluir = {b.upper() for b in cfg.get('excluir_bases', [])} | _BLOQUEADAS_BR | STABLES_FIXAS
    detectar_peg = bool(cfg.get('detectar_stable_peg', True))
    tk_cfg = carregar_config().get('tokenizadas', {})
    tokenizadas = {b.strip().upper() for b in (tk_cfg.get('bases', []) or [])}
    tk_min = float(tk_cfg.get('notional_min_24h', 100_000))
    try:
        from trendai_banco import conectar
        _con = conectar()
        for _r in _con.execute("SELECT symbol, categorias, nome FROM moedas_info"):
            _txt = (str(_r[1]) + " " + str(_r[2])).lower()
            if "tokenized stock" in _txt or "bstocks" in _txt or "tokenized etf" in _txt:
                tokenizadas.add(str(_r[0]).upper())
        _con.close()
    except Exception:
        pass

    ex = exchange_mercado(exchange)
    ex.load_markets()
    registrar(ex, 'exchange_info')
    tickers = ex.fetch_tickers()
    registrar(ex, 'tickers_24h')

    agora_ms = time.time() * 1000.0
    saida = []
    _bloq_br = []
    _peg = []
    for symbol, t in tickers.items():
        try:
            m = ex.markets.get(symbol) or {}
            if m.get('quote') != quote:
                continue
            if m.get('type') not in (None, 'spot'):
                continue
            if not m.get('active', True):
                continue
            base = (m.get('base') or symbol.split('/')[0]).upper()
            if base in _BLOQUEADAS_BR:
                _bloq_br.append(base)
                continue
            if _e_stable_ou_fiat(base, excluir) or _e_alavancado(base):
                continue
            eh_tk = base in tokenizadas
            # Rede de segurança p/ stablecoin ainda desconhecida: preço ~US$ 1,00
            # e faixa (máx-mín) de 24h <= 0,6% — nenhuma altcoin real fica tão
            # parada. Não vale p/ tokenizadas (preço de ação/ETF).
            if detectar_peg and not eh_tk:
                _last = float(t.get('last') or t.get('close') or 0.0)
                _hi = float(t.get('high') or 0.0)
                _lo = float(t.get('low') or 0.0)
                if (0.97 <= _last <= 1.03 and _hi > 0 and _lo > 0
                        and (_hi - _lo) / _last <= 0.006):
                    _peg.append(base)
                    continue
            # idade da listagem (onboardDate) quando disponível — NÃO se aplica
            # a ações tokenizadas (a empresa/ETF é antiga; novas listagens de
            # bStocks entram de imediato no rastreio)
            if not eh_tk:
                onboard = (m.get('info') or {}).get('onboardDate')
                if onboard:
                    try:
                        if (agora_ms - float(onboard)) < idade_min_dias * 86400_000:
                            continue
                    except Exception:
                        pass
            notional = float(t.get('quoteVolume') or 0.0)
            lim = tk_min if eh_tk else notional_min
            if notional < lim:
                continue
            saida.append({
                'symbol': symbol,
                'base': base,
                'notional': notional,
                'var24h': float(t.get('percentage') or 0.0),
            })
        except Exception:
            continue

    saida.sort(key=lambda d: d['notional'], reverse=True)
    # Tokenizadas NUNCA são cortadas pelo cap (max_moedas é teto do universo
    # cripto) — a carteira de ações precisa rastrear TODAS as listadas.
    # Mantém a ordenação por notional (amostra do breadth continua sendo a
    # dos maiores notionais) e anexa as tokenizadas que ficaram fora do corte.
    cortada = saida[:max_moedas]
    faltando_tk = [d for d in saida[max_moedas:] if d['base'] in tokenizadas]
    if _bloq_br and log:
        try:
            log(f"universo: {len(_bloq_br)} pares de moedas bloqueadas no Brasil "
                f"excluídos ({', '.join(sorted(set(_bloq_br)))})")
        except Exception:
            pass
    if _peg and log:
        try:
            log(f"universo: {len(_peg)} stablecoin(s) detectada(s) pelo peg e excluída(s) "
                f"({', '.join(sorted(set(_peg)))})")
        except Exception:
            pass
    return cortada + faltando_tk


def baixar_klines(symbol, timeframe, limite, exchange=None, con=None, usar_cache=True):
    """Klines via ccxt com cache SQLite. Retorna lista [ts, o, h, l, c, v] (floats)."""
    fechar = False
    if con is None:
        con = conectar()
        fechar = True
    try:
        if usar_cache:
            dados = klines_cache_ler(con, symbol, timeframe,
                                     _CACHE_IDADE.get(timeframe, 3600.0))
            if dados and len(dados) >= limite:
                return dados[-limite:]
        ex = exchange_mercado(exchange)
        velas = ex.fetch_ohlcv(symbol, timeframe=timeframe, limit=limite)
        registrar(ex, 'klines', peso=(1 if limite <= 100 else 2))
        dados = [[float(v) for v in v] for v in velas]
        if dados:
            klines_cache_gravar(con, symbol, timeframe, dados)
        return dados
    finally:
        if fechar:
            con.close()


def klines_para_df(velas):
    """Converte a lista de klines em DataFrame pandas (ts, open, high, low, close, volume)."""
    import pandas as pd
    return pd.DataFrame(velas, columns=['ts', 'open', 'high', 'low', 'close', 'volume']).astype(float)