import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import discord
from discord.ext import commands
from discord import app_commands
import re

from botdiscord.config import get_discord_token, load_config, get_languages
from botdiscord.database import init_db, get_active_languages, get_bot_languages, save_message
from botdiscord.ui import TranslationView, ConfigView
from botdiscord.translate import get_reverse_mapping, load_lang_mappings

load_config()

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    init_db()
    load_lang_mappings("discord")
    print(f"Bot Discord conectado como {bot.user}")
    try:
        synced = await bot.tree.sync()
        print(f"Sincronizados {len(synced)} comandos.")
    except Exception as e:
        print(e)

def get_active_langs_for_guild(guild_id):
    from botdiscord.translate import get_reverse_mapping, get_flag_mapping
    
    active = get_active_languages(guild_id)
    print(f"[BOT DEBUG] guild_id={guild_id}, active from db: {active}")
    if not active:
        active = get_bot_languages("discord")
        print(f"[BOT DEBUG] active from bot_languages: {active}")
    if not active:
        active = [lang["code"] for lang in get_languages()]
        print(f"[BOT DEBUG] active from config: {active}")
    
    reverse_mapping = get_reverse_mapping("discord")
    print(f"[BOT DEBUG] reverse_mapping: {reverse_mapping}")
    
    result = [reverse_mapping[l] for l in active if l in reverse_mapping]
    print(f"[BOT DEBUG] langs_to_show: {result}")
    return result

@bot.event
async def on_message(message):
    if message.author.bot:
        return

    text_content = message.content.strip()
    has_attachments = len(message.attachments) > 0
    has_embeds = len(message.embeds) > 0
    
    is_sticker = message.stickers
    is_gif_url = text_content.startswith('https://tenor.com/') or text_content.startswith('https://giphy.com/')
    is_discord_emoji = re.fullmatch(r'<(a?):[a-zA-Z0-9_]+:[0-9]+>', text_content)
    
    if is_sticker or is_gif_url or is_discord_emoji:
        return
    
    if text_content and len(text_content) < 2:
        return
    
    if not text_content and not has_attachments:
        return
    
    if has_attachments and not text_content:
        return

    active_langs = get_active_langs_for_guild(message.guild.id)
    if not active_langs:
        return

    import html
    text_escaped = html.escape(message.content)

    # Buscamos menciones que ya están escapadas (&lt;@...&gt;)
    mention_pattern = re.compile(r'&lt;@!?(\d+)&gt;|&lt;@&(\d+)&gt;|&lt;#(\d+)&gt;')
    mentions_map = {}
    
    def replace_mention(match):
        # Usamos una etiqueta autocerrada para que el traductor no intente cerrarla él mismo
        placeholder = f"<m{len(mentions_map)} />"
        # Guardamos la mención original (sin escapar) para restaurarla luego
        mentions_map[placeholder] = html.unescape(match.group(0))
        return placeholder
    
    text_to_translate = mention_pattern.sub(replace_mention, text_escaped)
    
    # Guardamos el mensaje en la base de datos para persistencia y caché
    save_message(message.id, message.guild.id, message.author.id, text_to_translate, mentions_map, 'discord')
    
    langs_to_show = active_langs

    if langs_to_show:
        print(f"[BOT DEBUG] Creating TranslationView with langs: {langs_to_show}")
        view = TranslationView(text_to_translate, langs_to_show, message, message.attachments, mentions_map)
        print(f"[BOT DEBUG] View created, sending message...")
        try:
            await message.reply("¿Traducir este mensaje?", view=view, mention_author=False)
            print(f"[BOT DEBUG] Message sent successfully")
        except Exception as e:
            print(f"[BOT DEBUG] Error sending message: {e}")

@bot.tree.command(name="configurar", description="Configura los idiomas de traducción para este servidor")
@app_commands.checks.has_permissions(administrator=True)
async def configurar(interaction: discord.Interaction):
    view = ConfigView(interaction.guild_id, "discord")
    await interaction.response.send_message(
        "Selecciona los idiomas que quieres habilitar para los botones de traducción:",
        view=view,
        ephemeral=True
    )

def run_discord_bot():
    token = get_discord_token()
    if not token or token == "TU_DISCORD_BOT_TOKEN":
        print("ERROR: Configura el token de Discord en config.yaml")
        return
    bot.run(token)

if __name__ == "__main__":
    run_discord_bot()
