from datetime import datetime
from .config import Config

# =============================================================================
# CONSTANTES GLOBALES DE PLANES (Para evitar errores de scope)
# =============================================================================
PLAN_NAMES = {
    'basic': 'BÁSICO',
    'intermediate': 'INTERMEDIO',
    'advanced': 'AVANZADO',
    'completed': 'PREMIUM',
    'free': 'GRATUITO',
    'expired': 'CADUCADO'
}

PLAN_EMOJIS = {
    'basic': '🟢',
    'intermediate': '🟠',
    'advanced': '🔵',
    'completed': '💎',
    'free': '🆓',
    'expired': '⚠️'
}

PLAN_BENEFITS = {
    'basic': [
        "• 4 análisis diarios (Mercado Spot)",
        "• 2 señales Top 6 criptomonedas",
        "• Indicadores básicos (RSI, MACD)",
        "• Acceso al bot de Telegram",
        "• Soporte por comunidad 24/7"
    ],
    'intermediate': [
        "• 8 señales Spot cada 12 horas",
        "• 3 señales de Futuros",
        "• 3 señales Top 6 criptomonedas",
        "• Indicadores Medios (Básicos + EMA)",
        "• Hasta 5 alertas personalizadas",
        "• Soporte prioritario 24/7"
    ],
    'advanced': [
        "• Análisis 24 horas (ilimitado)",
        "• Señales ilimitadas Spot y Futuros",
        "• Top 6 mejores Monedas",
        "• Indicadores Pro (Medios + Volume)",
        "• Soporte 1:1 con analistas",
        "• Alertas ilimitadas"
    ]
}

# =============================================================================
# BARRA DE CONFIANZA (Para mostrar visualmente la confianza de la señal)
# =============================================================================
def generate_confidence_bar(confidence: int) -> str:
    blocks = int(confidence / 10)
    filled = "█" * blocks
    empty = "░" * (10 - blocks)
    return f"[{filled}{empty}] {confidence}%"

# =============================================================================
# MENSAJES PARA LAS SEÑALES
# =============================================================================
def format_signal_message(signals: list, market_type: str) -> str:
    title = "🏆 SEÑALES PREMIUM - SPOT" if market_type == "spot" else "🏆 SEÑALES PREMIUM - FUTUROS"
    now = datetime.now().strftime("%H:%M:%S")
    
    msg = f"{title}\n⏰ {now}\n\n━━━━━━━━━━━━━━━━━━━━\n\n"
    
    for i, sig in enumerate(signals, 1):
        symbol = sig['symbol']
        direction_str = ""
        if market_type == "futures":
            symbol = symbol.replace("/", "")
            direction = sig['direction']
            direction_emoji = "🟢" if direction.upper() == "LONG" else "🔴" if direction.upper() == "SHORT" else ""
            direction_label = f"{direction_emoji} {direction}".strip()
            direction_str = f" - {direction_label}"
        conf_bar = generate_confidence_bar(sig['confidence'])
        
        msg += f"#{i}. {symbol}{direction_str}\n"
        msg += f"💰 Precio: ${sig['price']:.4f}\n"
        msg += f"📊 Confianza: {conf_bar}\n"
        msg += f"🎯 Entry: ${sig['entry']:.4f}\n"
        msg += f"⛔ Stop Loss: ${sig['sl']:.4f}\n"
        msg += f"✅ Take Profit 1: ${sig['tp1']:.4f}\n"
        msg += f"✅ Take Profit 2: ${sig['tp2']:.4f}\n\n"
        
        for note in sig['notes']:
            msg += f"📝 {note}\n"
            
        msg += "━━━━━━━━━━━━━━━━━━━━\n\n"
        
    if market_type == "futures":
        msg += "⚠️ Gestión de Riesgo: Se recomienda un apalancamiento máximo de 3x a 5x.\n\n"
        
    msg += "⚠️ Disclaimer: Esto no es consejo financiero. Opera siempre con gestión de riesgo (máx 2-3% por operación)."
    
    return msg

# =============================================================================
# MENSAJES PARA EL TOP 6 CRIPTOMONEDAS
# =============================================================================
def format_top_cryptos_message(symbols_data: list) -> str:
    msg = "🔥 *TOP 6 CRIPTOMONEDAS POR VOLUMEN (24H)*\n\n"
    for i, data in enumerate(symbols_data, 1):
        change_emoji = "🟢" if data['change'] >= 0 else "🔴"
        msg += f"{i}. *{data['symbol']}*\n"
        msg += f"   💵 Precio: ${data['price']:.4f}\n"
        msg += f"   {change_emoji} 24h: {data['change']:.2f}%\n"
        msg += f"   📊 Vol: ${data['volume']:,.0f}\n\n"
    return msg

# =============================================================================
# MENSAJES PARA EL PLAN DEL USUARIO
# =============================================================================
def format_plan_message(plan_info: dict) -> str:
    # === CASO 1: PLAN CADUCADO ===
    if plan_info.get('plan') == 'expired' or not plan_info.get('is_active', True):
        expiry_str = plan_info['expiry_date'].strftime('%d/%m/%Y %H:%M') if plan_info.get('expiry_date') else 'N/A'
        return (
            f"⚠️ <b>PLAN CADUCADO</b>\n\n"
            f"📅 Expiró el: {expiry_str}\n\n"
            f"Tu suscripción ha expirado. Renueva ahora para continuar disfrutando de KrakenEye.\n\n"
            f"🔗 Renovar aquí: {Config.SUBSCRIPTION_URL}"
        )
    
    # === CASO 2: PLAN GRATUITO ===
    if plan_info.get('plan') == 'free' or not plan_info.get('is_premium', False):
        expiry_info = ""
        if plan_info.get('expiry_date'):
            expiry_str = plan_info['expiry_date'].strftime('%d de %B de %Y, %I:%M %p')
            days_left = plan_info.get('days_left', 0)
            expiry_info = f"📅 Válido hasta: {expiry_str}\n"
            expiry_info += f"⏰ Días restantes: {days_left}\n"
        
        return (
            f"🆓 <b>PLAN GRATUITO</b>\n\n"
            f"{expiry_info}"
            f"Actualmente tienes acceso a las funcionalidades básicas.\n\n"
            f"🌟 <b>Funcionalidades incluidas:</b>\n"
            f"• Análisis de mercado Spot y Futuros\n"
            f"• Señales Ilimitadas por 24 horas\n"
            f"• Top 6 criptomonedas mas Populares\n\n"
            f"💎 <b>¡Mejora a Premium!</b> para acceder a:\n"
            f"• Análisis de Futuros\n"
            f"• Señales ilimitadas permanentes\n"
            f"• Alertas en tiempo real\n"
            f"• Soporte prioritario\n\n"
            f"🔗 <b>Adquiere tu plan aquí:</b> {Config.SUBSCRIPTION_URL}"
        )
    
    # === CASO 3: PLAN DE PAGO ===
    plan_slug = plan_info.get('plan', 'completed')
    plan_display = PLAN_NAMES.get(plan_slug, plan_slug.upper())
    plan_emoji = PLAN_EMOJIS.get(plan_slug, '💎')
    
    expiry_str = plan_info['expiry_date'].strftime('%d de %B de %Y, %I:%M %p') if plan_info.get('expiry_date') else 'N/A'
    days_left = plan_info.get('days_left', 0)
    hours_left = plan_info.get('hours_left', 0)
    
    plan_benefits = PLAN_BENEFITS.get(plan_slug, PLAN_BENEFITS['intermediate'])
    benefits_text = "\n".join(plan_benefits)
    
    return (
        f"{plan_emoji} PLAN {plan_display}\n\n"
        f"✅ Estado: Activo\n"
        f"📅 Expira: {expiry_str}\n"
        f"⏰ Días restantes: {days_left} días\n"
        f"🕐 Horas restantes: {hours_left} horas\n\n"
        f"🌟 <b>Beneficios incluidos:</b>\n"
        f"{benefits_text}\n\n"
        f"<b>¡Disfruta de todas las características premium!</b>"
    )

# =============================================================================
# MENSAJES PARA USUARIOS NO REGISTRADOS
# =============================================================================
def format_welcome_no_registered_message(username: str) -> str:
    """Mensaje para usuarios SIN registro en la BD"""
    return (
        f"👋 ¡Hola, {username}!\n\n"
        f"🎉 <b>Bienvenido a KrakenEye Academy</b>\n\n"
        f"📌 <b>Primeros pasos:</b>\n"
        f"1️⃣ Visita nuestra web: <b>{Config.SITE_URL}</b>\n"
        f"2️⃣ Regístrate y activa el <b>plan gratuito</b>\n"
        f"3️⃣ Vuelve al bot y comienza a recibir señales\n\n"
        f"🎁 <b>Plan Gratuito incluye:</b>\n"
        f"• Análisis de mercado Spot y Futuros\n"
        f"• Señales Ilimitadas\n"
        f"• Top 6 criptomonedas mas Populares\n\n"
        f"⚠️ Todo esto por 24 horas para que valides la calidad\n\n"
        f"💎 <b>¿Quieres más?</b> Adquiere un plan de pago y obtén:\n"
        f"• Análisis de Futuros (Long/Short)\n"
        f"• Señales ilimitadas\n"
        f"• Alertas en tiempo real\n"
        f"• Soporte prioritario\n\n"
        f"🔗 <b>Comenzar ahora:</b> {Config.SUBSCRIPTION_URL}"
    )

# =============================================================================
# MENSAJES DE BIENVENIDA (Función auxiliar por si se usa en otro módulo)
# =============================================================================
def format_welcome_message(user: dict, plan: dict) -> str:
    plan_slug = plan.get('plan', 'free')
    plan_display = PLAN_NAMES.get(plan_slug, plan_slug.upper())
    plan_emoji = PLAN_EMOJIS.get(plan_slug, '💎')
    
    expiry_str = plan['expiry_date'].strftime('%d de %B de %Y, %I:%M %p') if plan.get('expiry_date') else 'N/A'
    days_left = plan.get('days_left', 0)
    hours_left = plan.get('hours_left', 0)
    
    plan_benefits = PLAN_BENEFITS.get(plan_slug, PLAN_BENEFITS['intermediate'])
    benefits_text = "\n".join(plan_benefits)

    return (
        f"{plan_emoji} PLAN {plan_display}\n\n"
        f"✅ Estado: Activo\n"
        f"📅 Expira: {expiry_str}\n"
        f"⏰ Días restantes: {days_left} días\n"
        f"🕐 Horas restantes: {hours_left} horas\n\n"
        f"🌟 <b>Beneficios incluidos:</b>\n"
        f"{benefits_text}\n\n"
        f"<b>¡Disfruta de todas las características premium!</b>"
    )

# =============================================================================
# FORMATEO DE RECOMENDACIONES DE LAS TOP 6 CRIPTOMONEDAS
# =============================================================================
def format_top_cryptos_recommendations(signals: list) -> str:
    """
    Formata las recomendaciones de las Top 6 Criptomonedas Populares.
    """
    from datetime import datetime
    now = datetime.now().strftime("%H:%M:%S")
    
    msg = f"🏆 TOP 6 CRIPTOMONEDAS POPULARES\n"
    msg += f"⏰ {now}\n\n"
    msg += f"━━━━━━━━━━━━━━━━━━━━\n\n"
    
    for i, sig in enumerate(signals, 1):
        symbol = sig['symbol'].replace("/", "")
        direction = sig.get('direction', '')
        direction_emoji = "🟢" if direction.upper() == "LONG" else "🔴" if direction.upper() == "SHORT" else ""
        direction_label = f"{direction_emoji} {direction}".strip()
        direction_str = f" - {direction_label}" if direction_label else ""
        conf_bar = generate_confidence_bar(sig['confidence'])
        
        msg += f"#{i}. {symbol}{direction_str}\n"
        msg += f"💰 Precio: ${sig['price']:.4f}\n"
        msg += f"📊 Confianza: {conf_bar}\n"
        msg += f"🎯 Entry: ${sig['entry']:.4f}\n"
        msg += f"⛔ Stop Loss: ${sig['sl']:.4f}\n"
        msg += f"✅ Take Profit 1: ${sig['tp1']:.4f}\n"
        msg += f"✅ Take Profit 2: ${sig['tp2']:.4f}\n\n"
        
        for note in sig['notes']:
            msg += f"📝 {note}\n"

        # Agregar cambio 24h si está disponible
        if 'change_24h' in sig:
            change_emoji = "📈" if sig['change_24h'] > 0 else "📉"
            msg += f"{change_emoji} Cambio 24h: {sig['change_24h']:.2f}%\n"
        
        msg += "━━━━━━━━━━━━━━━━━━━━\n\n"
    
    msg += "⚠️ Gestión de Riesgo: Se recomienda un apalancamiento máximo de 3x a 5x.\n\n"
    msg += "⚠️ Disclaimer: Esto no es consejo financiero. Opera siempre con gestión de riesgo (máx 2-3% por operación)."
    
    return msg