# -*- coding: utf-8 -*-
"""TrendAI — features por moeda × horizonte (7d / 4w / 13w).

Cada horizonte usa o timeframe adequado (4h p/ 7d; 1d p/ 4w e 13w) e produz
os cinco blocos de fatores do plano:
momentum | forca_relativa | volume | estrutura | risco
"""
import math

import pandas as pd

import trendai_indicadores as ind
from trendai_conexao import carregar_config
from trendai_universo import baixar_klines, klines_para_df

_HORIZ_TF = {'7d': ('4h', 60), '4w': ('1d', 60), '13w': ('1d', 120)}


def _clamp(x, lo, hi):
    return max(lo, min(hi, x))


def _retorno_pct(closes, n):
    """Variação % das últimas n velas (retorno do período)."""
    if len(closes) < n + 1:
        return 0.0
    a = float(closes.iloc[-n - 1])
    b = float(closes.iloc[-1])
    return (b / a - 1.0) * 100.0 if a > 0 else 0.0


def features_moeda(symbol, base_info, con=None, exchange=None, btc_closes=None):
    """Calcula as features de todos os horizontes de uma moeda.

    btc_closes: dict horizonte -> pd.Series de closes do BTC/USDT no mesmo
    timeframe (para força relativa). Se None, a RS fica neutra.
    Retorna dict {'symbol', 'notional', 'var24h', 'horizontes': {h: {...}}}
    ou None se dados insuficientes.
    """
    cfg = carregar_config()
    params = cfg.get('parametros', {})
    rsi_lo = float(params.get('rsi_min_saudavel', 50))
    rsi_hi = float(params.get('rsi_max_saudavel', 70))
    vr_cap = float(params.get('vr_cap', 3.0))
    atr_min = float(params.get('atr_pct_ideal_min', 0.3))
    atr_max = float(params.get('atr_pct_ideal_max', 3.0))
    sqz_max = float(params.get('squeeze_bandwidth_max', 0.02))
    caps_ret = params.get('retorno_cap_pct', {})
    caps_rs = params.get('rs_cap_pct', {})

    saida = {'symbol': symbol, 'base': base_info.get('base'),
             'notional': float(base_info.get('notional') or 0.0),
             'var24h': float(base_info.get('var24h') or 0.0),
             'horizontes': {}}

    for h, (tf, limite) in _HORIZ_TF.items():
        try:
            velas = baixar_klines(symbol, tf, limite, exchange=exchange, con=con)
        except Exception:
            # Bitget pode indispor um horizonte (ex.: history 13w) sem derrubar
            # os demais — continua p/ o próximo horizonte (tolerância).
            continue
        if not velas or len(velas) < 35:
            continue
        df = klines_para_df(velas)
        c, hi, lo, vol = df['close'], df['high'], df['low'], df['volume']

        n_per = min({'7d': 42, '4w': 28, '13w': 91}[h], len(df) - 2)

        # --- Momentum ---
        ret = _retorno_pct(c, n_per)
        rsi_v = float(ind.rsi(c, 14).iloc[-1])
        hist = float(ind.macd_hist(c).iloc[-1])
        hist_prev = float(ind.macd_hist(c).iloc[-3]) if len(c) > 3 else hist
        ema21 = ind.ema(c, 21)
        ema55 = ind.ema(c, 55)
        close_now = float(c.iloc[-1])
        estrutura_ema = (1 if close_now > float(ema21.iloc[-1]) else 0) + \
                        (1 if float(ema21.iloc[-1]) > float(ema55.iloc[-1]) else 0)

        cap_r = float(caps_ret.get(h, 30))
        if ret >= 0:
            p_mom = 40.0 * _clamp(ret / cap_r, 0.0, 1.0)
        else:
            p_mom = 20.0 + 20.0 * _clamp(ret / cap_r, -1.0, 0.0)
        p_mom += 25.0 * _clamp(1.0 - max(0.0, rsi_lo - rsi_v, rsi_v - rsi_hi) / 20.0, 0.0, 1.0)
        p_mom += 20.0 * (1.0 if hist > 0 else (0.5 if hist > hist_prev else 0.0))
        p_mom += 15.0 * (estrutura_ema / 2.0)

        # --- Força relativa vs BTC ---
        if btc_closes and h in btc_closes and len(btc_closes[h]) > n_per:
            ret_btc = _retorno_pct(btc_closes[h], n_per)
            rs = ret - ret_btc
        else:
            ret_btc, rs = 0.0, 0.0
        cap_s = float(caps_rs.get(h, 20))
        p_rs = 100.0 * _clamp((rs + cap_s * 0.5) / cap_s, 0.0, 1.0)

        # --- Volume (ratio 24h vs base ~7 dias, adaptado ao timeframe) ---
        # FIX (03/11/2026): o cálculo antigo exigia 96 velas (só havia no 1h) e nos
        # timeframes 4h/1d caía no fallback vr=1.00 — a coluna "Vol (24h)" saía
        # 1,00x para TODAS as moedas (bug visto no print do 1º ciclo no VPS).
        # Agora: média por vela das últimas n24 velas (~24h) sobre a média por vela
        # da janela anterior (base de até 7 dias), independente do timeframe.
        n24 = {'1h': 24, '4h': 6, '1d': 1}.get(tf, 6)
        qv = vol * c
        recentes = qv.iloc[-n24:]
        vol_recente = float(recentes.mean()) if len(recentes) else 0.0
        base_ini = max(0, len(qv) - n24 * 8)
        fatia_base = qv.iloc[base_ini:max(base_ini, len(qv) - n24)]
        vol_base = float(fatia_base.mean()) if len(fatia_base) else vol_recente
        vr = (vol_recente / vol_base) if vol_base > 0 else 0.0
        obv_s = ind.obv(c, vol)
        obv_ante = float(obv_s.iloc[-10]) if len(obv_s) >= 10 else float(obv_s.iloc[0])
        obv_subindo = float(obv_s.iloc[-1]) > obv_ante
        p_vol = 60.0 * _clamp(vr / vr_cap, 0.0, 1.0) + \
            25.0 * _clamp(math.log10(max(saida['notional'], 1.0) / 1e6) / 2.0, 0.0, 1.0) + \
            (15.0 if obv_subindo else 0.0)

        # --- Estrutura de alta ---
        janelas = [df.iloc[i:i + 5] for i in range(len(df) - 25, len(df) - 5, 5)]
        if len(janelas) >= 3:
            highs = [float(w['high'].max()) for w in janelas]
            lows = [float(w['low'].min()) for w in janelas]
            hh = sum(1 for i in range(1, len(highs)) if highs[i] > highs[i - 1])
            hl = sum(1 for i in range(1, len(lows)) if lows[i] > lows[i - 1])
            estrutura = (hh + hl) / (2.0 * (len(highs) - 1))
        else:
            estrutura = 0.5
        pico = float(hi.iloc[-n_per:].max())
        queda_pico = ((pico - close_now) / pico * 100.0) if pico > 0 else 0.0
        e21 = float(ema21.iloc[-1])
        ema21_dist = (close_now / e21 - 1.0) * 100.0 if e21 > 0 else 0.0
        p_est = 55.0 * _clamp(estrutura, 0.0, 1.0) + \
            25.0 * _clamp(1.0 - max(0.0, ema21_dist) / 8.0, 0.0, 1.0) + \
            20.0 * _clamp(1.0 - max(0.0, queda_pico - 2.0) / 15.0, 0.0, 1.0)

        # --- Risco / volatilidade ---
        pc1 = c.shift(1)
        tr = pd.concat([hi - lo, (hi - pc1).abs(), (lo - pc1).abs()], axis=1).max(axis=1)
        atr_v = float(tr.ewm(alpha=1 / 14, adjust=False).mean().iloc[-1])
        atr_pct = (atr_v / close_now * 100.0) if close_now > 0 else 0.0
        _, _, _, bandwidth, _ = ind.bbands(c, 20, 2.0)
        bw = float(bandwidth.iloc[-1])
        if atr_min <= atr_pct <= atr_max:
            p_risco = 70.0
        else:
            p_risco = 70.0 * _clamp(1.0 - abs(atr_pct - (atr_min + atr_max) / 2) / 3.0, 0.0, 1.0)
        if bw <= sqz_max:
            p_risco += 30.0  # squeeze: compressão de banda = combustível p/ alta
        else:
            p_risco += 30.0 * _clamp(1.0 - (bw - sqz_max) / 0.1, 0.0, 1.0)

        saida['horizontes'][h] = {
            'retorno': round(ret, 2),
            'retorno_btc': round(ret_btc, 2),
            'rs_btc': round(rs, 2),
            'rsi': round(rsi_v, 1),
            'macd_hist': hist,
            'volume_ratio': round(vr, 2),
            'obv_subindo': bool(obv_subindo),
            'estrutura_hh_hl': round(estrutura, 2),
            'queda_pico_pct': round(queda_pico, 2),
            'ema21_dist_pct': round(ema21_dist, 2),
            'atr_pct': round(atr_pct, 3),
            'bb_bandwidth': round(bw, 4),
            'fatores': {
                'momentum': round(p_mom, 1),
                'forca_relativa': round(p_rs, 1),
                'volume': round(p_vol, 1),
                'estrutura': round(p_est, 1),
                'risco': round(p_risco, 1),
            },
        }

    if not saida['horizontes']:
        return None

    # pos24h (veto de exaustão) e preço atual — timeframe 1h
    try:
        v1h = baixar_klines(symbol, '1h', 48, exchange=exchange, con=con)
        if v1h and len(v1h) >= 24:
            df1 = klines_para_df(v1h).iloc[-24:]
            lo24 = float(df1['low'].min())
            hi24 = float(df1['high'].max())
            la = float(df1['close'].iloc[-1])
            saida['preco'] = la
            saida['pos24h'] = round((la - lo24) / (hi24 - lo24), 3) if hi24 > lo24 else 0.5
        else:
            saida['preco'] = None
            saida['pos24h'] = None
    except Exception:
        saida['preco'] = None
        saida['pos24h'] = None

    return saida