# -*- 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))
    # Floor de liquidez para evitar pares mortos/illíquidos da Bitget que causam
    # erro 48001 / dados vazios no cálculo de features.
    notional_floor = float(cfg.get('notional_min_24h', 1_000_000))
    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))
    # Bitget: variantes R+core ↔ core+B (RSPY ↔ SPYB, RAAPL ↔ AAPLB, ...).
    # Sem isto, `eh_tk` nunca casava (universo: 0 tokenizadas no ciclo #156).
    def _var_bitget(b):
        b = str(b or '').upper()
        v = {b}
        if b.startswith('R') and len(b) >= 2:
            core = b[1:]
            v.update({core, core + 'B'})
        if b.endswith('B') and len(b) >= 2:
            core = b[:-1]
            v.update({core, 'R' + core, 'R' + core + 'B'})
        return v
    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
    _tk_exp = set(tokenizadas)
    for _b in list(tokenizadas):
        _tk_exp |= _var_bitget(_b)

    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 _tk_exp
            # 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_floor
            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 _tk_exp]
    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


# Duração de cada timeframe em ms (para calcular `since` no fetch_ohlcv da Bitget)
_TF_MS = {'1h': 3600_000, '4h': 4 * 3600_000, '1d': 24 * 3600_000}


def _fetch_ohlcv_bitget(ex, symbol, timeframe, limite):
    """fetch_ohlcv na Bitget via endpoint de HISTÓRIA (até 200 velas).

    Contexto (ciclo #154, features calculadas: 0):
    - `fetch_ohlcv` sem `since` usa o endpoint *recent*
      (`publicSpotGetV2SpotMarketCandles`), que rejeita limites grandes
      (ex.: 1d/120 do horizonte 13w) com 48001 "Parameter validation failed null".
    - Com `since` calculado + `params={'useHistoryEndpoint': True}` o ccxt
      entra no `history-candles` (até 200 velas). 120 cabe.
    - Timeout local forçado em 10s: no VPS o socket pode pendurar sem
      timeout (hang até timeout implícito do ccxt).
    """
    dur_ms = _TF_MS.get(timeframe, 3600_000)
    agora_ms = int(time.time() * 1000)
    since_ms = agora_ms - (int(limite) + 2) * dur_ms
    try:
        # Timeout fixo 10s: a instância pública pode estar com timeout
        # herdado grande (10s no diag18); no VPS o socket pendura sem
        # ele. ex.timeout é em ms no ccxt.
        ex.timeout = 10000
    except Exception:
        pass
    velas = None
    try:
        velas = ex.fetch_ohlcv(symbol, timeframe=timeframe, limit=int(limite),
                               since=since_ms,
                               params={'useHistoryEndpoint': True})
    except Exception:
        pass
    if velas:
        return velas
    try:
        velas = ex.fetch_ohlcv(symbol, timeframe=timeframe, limit=int(limite),
                               since=since_ms)
    except Exception:
        pass
    if velas:
        return velas
    # Fallback recent
    return ex.fetch_ohlcv(symbol, timeframe=timeframe, limit=int(limite))


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:
        # Cache: só usa se estiver completo e não envenenado (<35 velas).
        # Um cache curto pode vir de falha parcial e gera features zeradas
        # silenciosas (ex.: 5 entradas 1d com <35 velas no diag12).
        if usar_cache:
            dados = klines_cache_ler(con, symbol, timeframe,
                                     _CACHE_IDADE.get(timeframe, 3600.0))
            if dados and len(dados) >= max(limite, 35):
                return dados[-limite:]
        ex = exchange_mercado(exchange)
        velas = _fetch_ohlcv_bitget(ex, symbol, timeframe, limite)
        registrar(ex, 'klines', peso=(1 if limite <= 100 else 2))
        dados = [[float(v) for v in v] for v in (velas or [])]
        if dados and len(dados) >= 35:
            klines_cache_gravar(con, symbol, timeframe, dados)
        return dados[-int(limite):] if dados else []
    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)