# from aiogram.methods import SendMessageDraft
from aiogram import F
from aiogram.types import (
    CallbackQuery,
    InlineKeyboardButton,
    InlineKeyboardMarkup,
)

from commands import *
from config import *
from supergenerator import *


@router.callback_query(F.data.startswith("prov%"))
async def select_provider_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 3)
    user_id, provider = data[1], data[2]

    if user_id != current_user_id:
        await callback.answer("не для тебя.")
        return

    config = get_user_config(user_id)
    user_model = config.get("model")
    
    buttons = []

    i = 0

    for model in MODELS.get(provider):
        i += 1
        if f"{provider}*{model}" == user_model:
            text = f"{model} ✅"
        else:
            text = model
        
        if MODELS[provider][model].get("alias"):
            model = MODELS[provider][model].get("alias")

        if not i % 2:
            buttons[len(buttons)-1] +=[
                InlineKeyboardButton(
                    text=text, callback_data=f"set_model%{user_id}%{provider}*{model}"
                )
            ]
        else:
            buttons.append(
                [
                    InlineKeyboardButton(
                        text=text, callback_data=f"set_model%{user_id}%{provider}*{model}"
                    )
                ]
            )

    if not buttons:
        buttons = [
            [
                InlineKeyboardButton(
                    text="🚫 нет моделей", callback_data=f"models%{user_id}"
                )
            ]
        ]

    buttons.append(
        [InlineKeyboardButton(text="⬅️ назад", callback_data=f"models%{user_id}")]
    )

    await callback.message.edit_text(
        f"выбран провайдер: {PROVIDERS.get(provider).get('name')}\nвыбери модель:",
        reply_markup=InlineKeyboardMarkup(inline_keyboard=buttons),
    )
    await callback.answer()


@router.callback_query(F.data.startswith("models%"))
async def models_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 1)
    user_id = data[1]
    if user_id == current_user_id:
        config = get_user_config(user_id)

        buttons = []

        i = 0
        
        for provider in MODELS:
            i += 1
            if not i % 2:
                buttons[len(buttons)-1] +=[
                    InlineKeyboardButton(
                        text=PROVIDERS.get(provider).get("name"), 
                        callback_data=f"prov%{user_id}%{provider}"
                    )
                ]
            else:
                buttons.append(
                    [
                        InlineKeyboardButton(
                            text=PROVIDERS.get(provider).get("name"),
                            callback_data=f"prov%{user_id}%{provider}",
                        )
                    ]
                )

        if not buttons:
            buttons.append(
                [
                    InlineKeyboardButton(
                        text="🚫 нет провайдеров!", callback_data=f"settings%{user_id}"
                    )
                ]
            )

        buttons.append(
            [InlineKeyboardButton(text="⬅️ назад", callback_data=f"settings%{user_id}")]
        )

        await callback.message.edit_text(
            "выбери провайдера:",
            reply_markup=InlineKeyboardMarkup(inline_keyboard=buttons),
        )
        await callback.answer()
    else:
        await callback.answer("не тыкай. это не для тебя.")


@router.callback_query(F.data.startswith("set_model%"))
async def set_model_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 2)
    user_id, new_model = data[1], data[2]
    provider = data[2].split("*", 1)[0]
    amodel = data[2].split("*", 1)[1]
    new_model = provider + "*" + amodel
    
    for model in MODELS.get(provider):
        nmodel = MODELS[provider][model].get("alias") or None
        if nmodel == amodel:
            new_model = provider + "*" + model
            
    if user_id == current_user_id:
        current_config = get_user_config(user_id)
        set_user_config(
            user_id, 
            new_model, 
            current_config.get("stream", True), 
            current_config.get("call"), 
            current_config.get("prompt"), 
            current_config.get("notify"),
            current_config.get("markdown")
        )
        await callback.message.edit_text(f"выбрана модель: `{new_model}`")
        await callback.answer(f"выбрано: {new_model}")
    else:
        await callback.answer("нет, не трогай")



@router.callback_query(F.data.startswith("prompts%"))
async def prompts_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 1)
    user_id = data[1]
    if user_id == current_user_id:
        config = get_user_config(user_id)
        prompt  = config.get("prompt")

        buttons = []
        i = 0
        
        for name in SYSTEM_PROMPTS:
            i += 1
            text = name
            if prompt == name:
                text += " ✅"

            if not i % 2:
                buttons[len(buttons)-1] +=[
                    InlineKeyboardButton(
                        text=text, 
                        callback_data=f"set_prompt%{user_id}%{name}"
                    )
                ]
            else:
                buttons.append(
                    [
                        InlineKeyboardButton(
                            text=text,
                            callback_data=f"set_prompt%{user_id}%{name}",
                        )
                    ]
                )

        if not buttons:
            buttons.append(
                [
                    InlineKeyboardButton(
                        text="🚫 нет промптов!", callback_data=f"settings%{user_id}"
                    )
                ]
            )

        buttons.append(
            [InlineKeyboardButton(text="⬅️ назад", callback_data=f"settings%{user_id}")]
        )

        await callback.message.edit_text(
            "выбери системный промпт:",
            reply_markup=InlineKeyboardMarkup(inline_keyboard=buttons),
        )
        await callback.answer()
    else:
        await callback.answer("не тыкай. это не для тебя.")



@router.callback_query(F.data.startswith("set_prompt%"))
async def set_prompt_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 2)
    user_id = data[1]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return

    new_status = callback.data.split("%")[2]

    config = get_user_config(user_id)
    set_user_config(
        user_id, 
        config.get("model"), 
        config.get("stream"), 
        config.get("call"), 
        new_status, 
        config.get("notify"),
        config.get("markdown")
    )
    await callback.answer("da поменял на " + new_status)
    await settings_handler(callback)


@router.callback_query(F.data.startswith("settings%"))
async def settings_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 1)
    user_id = data[1]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай")
        return

    await settings_handler(callback)


@router.callback_query(F.data.startswith("set_stream%"))
async def set_stream_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 2)
    user_id = data[1]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return

    new_status = callback.data.split("%")[2]

    config = get_user_config(user_id)
    if new_status == "native" or new_status == "edit":
        set_user_config(
            user_id, 
            config.get("model"), 
            new_status, 
            config.get("call"), 
            config.get("prompt"), 
            config.get("notify"),
            config.get("markdown"),
        )
    else:
        set_user_config(
            user_id, 
            config.get("model"), 
            "none", 
            config.get("call"), 
            config.get("prompt"), 
            config.get("notify"),
            config.get("markdown"),
        )
    await settings_handler(callback)


@router.callback_query(F.data.startswith("set_call%"))
async def set_call_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 2)
    user_id = data[1]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return

    new_status = callback.data.split("%")[2]

    config = get_user_config(user_id)
    set_user_config(
        user_id, 
        config.get("model"), 
        config.get("stream"), 
        new_status, 
        config.get("prompt"), 
        config.get("notify"),
        config.get("markdown"),
    )
    await settings_handler(callback)


@router.callback_query(F.data.startswith("set_notify%"))
async def set_notify_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 2)
    user_id = data[1]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return

    new_status = callback.data.split("%")[2]

    config = get_user_config(user_id)
    set_user_config(
        user_id, 
        config.get("model"), 
        config.get("stream"), 
        config.get("call"), 
        config.get("prompt"), 
        new_status,
        config.get("markdown"),
    )
    await settings_handler(callback)


@router.callback_query(F.data.startswith("set_markdown%"))
async def set_markdown_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 2)
    user_id = data[1]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return

    new_status = data[2]

    config = get_user_config(user_id)
    set_user_config(
        user_id, 
        config.get("model"), 
        config.get("stream"), 
        config.get("call"), 
        config.get("prompt"), 
        config.get("notify"), 
        new_status,
    )
    await settings_handler(callback)


@router.callback_query(F.data.startswith("new_md%"))
async def set_markdown_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 2)
    user_id = data[1]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return
    config = get_user_config(user_id)
    set_user_config(
        user_id, 
        config.get("model"), 
        config.get("stream"), 
        config.get("call"), 
        config.get("prompt"), 
        config.get("notify"), 
        "new",
    )
    await callback.answer("выбран новый стиль!!")


@router.callback_query(F.data.startswith("old_md%"))
async def set_markdown_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 2)
    user_id = data[1]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return
    config = get_user_config(user_id)
    set_user_config(
        user_id, 
        config.get("model"), 
        config.get("stream"), 
        config.get("call"), 
        config.get("prompt"), 
        config.get("notify"), 
        "old",
    )
    await callback.answer("выбран старый стиль!!")


@router.callback_query(F.data == "start")
async def start_callback(callback: CallbackQuery):
    await callback.message.edit_text(
        "✅ я рад что вас заинтересовать✅✅ а теперь напише любое сообщение и свободный узбек вам ответит✅\n\n"
        "/start - ага старт\n"
        "/clear - очистить контекст✅\n"
        "/settings - настройки✅\n"
        "/prompt - системный промпт узбека"
    )
    await callback.answer()


@router.callback_query(F.data.startswith("about%"))
async def about_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 1)
    user_id = data[1]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай")
        return

    buttons = [
        [InlineKeyboardButton(text="назад", callback_data=f"settings%{user_id}")]
    ]

    await callback.message.edit_text(
        ABOUT_BOT,
        reply_markup=InlineKeyboardMarkup(inline_keyboard=buttons),
    )

    await callback.answer()


@router.callback_query(F.data.startswith("donate%"))
async def donate_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 1)
    user_id = data[1]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай")
        return

    buttons = [
        [InlineKeyboardButton(text="назад", callback_data=f"settings%{user_id}")],
    ]

    await callback.message.edit_text(
        "слушай сюда✅ если хочешь чтобы я не сдох от голода и не начал "
        "писать на китайском✅ кидай сюда монеты👍\n\n"
        "наполни чан узбекгпта на плов✅ а то мозги скрипят как старый таган ✅\n\n"
        "ссылка внизу👍 whoever хочет быть красавчиком✅ кидай сколько не жалко👍\n\n"
        f"{DONATE_LINK}",
        reply_markup=InlineKeyboardMarkup(inline_keyboard=buttons),
    )

    await callback.answer()
