import discord
from discord.ext import commands
from discord import app_commands
import aiohttp

from botdiscord.config import get_libretranslate_url
from botdiscord.database import init_db, get_active_languages, set_active_languages

lang_mapping = {
    "Inglés": "en",
    "Portugués": "pt",
    "Francés": "fr",
    "Alemán": "de",
    "Italiano": "it",
    "Español": "es"
}

async def translate_text(text, target_lang):
    url = get_libretranslate_url()
    if not url:
        return "Error: URL de LibreTranslate no configurada"
    
    payload = {
        "q": text,
        "source": "auto",
        "target": lang_mapping.get(target_lang, target_lang),
        "format": "text"
    }
    async with aiohttp.ClientSession() as session:
        async with session.post(url, json=payload) as resp:
            if resp.status == 200:
                data = await resp.json()
                return data.get("translatedText", "Error en la traducción.")
            else:
                return f"Error de API: {resp.status}"

class TranslationView(discord.ui.View):
    def __init__(self, text, languages, original_message):
        super().__init__(timeout=None)
        self.text = text
        self.original_message = original_message
        for lang in languages:
            self.add_item(TranslationButton(lang, text))

class TranslationButton(discord.ui.Button):
    def __init__(self, lang_name, text):
        super().__init__(label=f"Traducir a {lang_name}", style=discord.ButtonStyle.primary)
        self.lang_name = lang_name
        self.text = text

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.defer(ephemeral=True)
        translated = await translate_text(self.text, self.lang_name)
        await interaction.followup.send(f"**Traducción ({self.lang_name}):**\n{translated}", ephemeral=True)

class ConfigSelect(discord.ui.Select):
    def __init__(self, guild_id):
        active = get_active_languages(guild_id)
        options = [
            discord.SelectOption(label=name, value=name, default=(lang_mapping[name] in active))
            for name in lang_mapping.keys()
        ]
        super().__init__(placeholder="Selecciona los idiomas activos...", min_values=0, max_values=len(options), options=options)

    async def callback(self, interaction: discord.Interaction):
        guild_id = interaction.guild_id
        selected_codes = [lang_mapping[val] for val in self.values]
        set_active_languages(guild_id, selected_codes)
        await interaction.response.send_message(f"Configuración actualizada: {', '.join(self.values)}", ephemeral=True)

class ConfigView(discord.ui.View):
    def __init__(self, guild_id):
        super().__init__()
        self.add_item(ConfigSelect(guild_id))

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

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

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

    text_content = message.content.strip()
    if not text_content:
        return

    import re
    is_only_emoji = re.fullmatch(r'<(a?):[a-zA-Z0-9_]+:[0-9]+>', text_content)
    if is_only_emoji:
        return

    if not text_content and message.stickers:
        return

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

    text_to_translate = message.clean_content
    
    reverse_mapping = {v: k for k, v in lang_mapping.items()}
    langs_to_show = [reverse_mapping[l] for l in active_langs if l in reverse_mapping]

    if langs_to_show:
        view = TranslationView(text_to_translate, langs_to_show, message)
        await message.reply("¿Traducir este mensaje?", view=view, mention_author=False)

@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)
    await interaction.response.send_message("Selecciona los idiomas que quieres habilitar para los botones de traducción:", view=view, ephemeral=True)

if __name__ == "__main__":
    from botdiscord.config import get_discord_token
    token = get_discord_token()
    if token:
        bot.run(token)
    else:
        print("Error: No se ha configurado el token de Discord")
