import random

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"),
            current_config.get("prompts")
        )
        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)

        user_prompts_count = len(config["prompts"])
        system_prompts_count = len(SYSTEM_PROMPTS)
        
        buttons = [
            [
                InlineKeyboardButton(text=f"✅ стандартные промпты ({system_prompts_count})", callback_data=f"system_prompts%{user_id}"),
            ],
            [
                InlineKeyboardButton(text=f"🤝 твои промпты ({user_prompts_count})", callback_data=f"user_prompts%{user_id}"),
            ],
            [
                InlineKeyboardButton(text="⬅️ назад", callback_data=f"settings%{user_id}"),
            ]
        ]

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


@router.callback_query(F.data.startswith("vps%"))
async def view_system_prompt_callback(callback: CallbackQuery, dataalo=""):
    current_user_id = str(callback.from_user.id)
    if dataalo != "":
        data = dataalo
    else:
        data = callback.data

    data = data.split("%", 3)
        
    user_id = data[1]
    prompt_id = data[2]
    if user_id != current_user_id:
        await callback.answer("pashol naxxuy")
        return
    
    config = get_user_config(user_id)
    prompt = config.get("prompt", "")

    if prompt_id in SYSTEM_PROMPTS:
        p = SYSTEM_PROMPTS.get(prompt_id)
    else:
        await callback.answer("не нашёл такого промпта!")
        return

    prompt_name = p.get("name")
    prompt_text = p.get("text")

    if prompt == prompt_id:
        prompt_apply_t = "✅ установлен"
    else:
        prompt_apply_t = "✅ установить"        

    buttons = [
        [
            InlineKeyboardButton(text=prompt_apply_t, callback_data=f"sp%{user_id}%0%{prompt_id}%3"),
        ],
        [
            InlineKeyboardButton(text="⬅️ назад", callback_data=f"system_prompts%{user_id}"),
        ]
    ]

    await callback.message.edit_text(
        f"название: `{prompt_name}`\n"
        f"id: `{prompt_id}`\n"
        f"```prompt\n{prompt_text}\n```",
        reply_markup=InlineKeyboardMarkup(inline_keyboard=buttons),
    )
    await callback.answer()



@router.callback_query(F.data.startswith("vp%"))
async def view_prompt_callback(callback: CallbackQuery, dataalo=""):
    current_user_id = str(callback.from_user.id)
    if dataalo != "":
        data = dataalo
    else:
        data = callback.data
    data = data.split("%", 2)
    user_id = data[1]
    prompt_id = data[2]
    if user_id != current_user_id:
        await callback.answer("pashol naxxuy")
        return
    
    config = get_user_config(user_id)
    prompt = config.get("prompt", "")
    prompts = config.get("prompts", {})

    if prompt_id in prompts:
        p = prompts.get(prompt_id)
    else:
        await callback.answer("промпта нет у тебя такого")
        return

    prompt_pub = p.get("public")
    prompt_f = p.get("filer")
    prompt_name = p.get("name")

    if prompt == prompt_id:
        prompt_apply_t = "✅ установлен"
    else:
        prompt_apply_t = "✅ установить"        

    if prompt_pub:
        prompt_pub_t = "✅ публичный"
        prompt_pub_t2 = "🚫 сделать приватным"
    else:
        prompt_pub_t = "🚫 приватный"
        prompt_pub_t2 = "✅ сделать публичным"

    if prompt_f:
        prompt_f_t = "как файл"
    else:
        prompt_f_t = "как сообщение"

    buttons = [
        [
            InlineKeyboardButton(text="✏️ изменить", callback_data=f"ed%{user_id}%{prompt_id}"),
            InlineKeyboardButton(text="❌ удалить", callback_data=f"dp%{user_id}%{prompt_id}"),
            
        ],
        [
            InlineKeyboardButton(text=prompt_pub_t2, callback_data=f"eds%{user_id}%{prompt_id}"),
            InlineKeyboardButton(text=f"📂 {prompt_f_t}", callback_data=f"edf%{user_id}%{prompt_id}"),
        ],
        [
            InlineKeyboardButton(text="💬 текст", callback_data=f"vt%{user_id}%{prompt_id}"),
            InlineKeyboardButton(text=prompt_apply_t, callback_data=f"sp%{user_id}%0%{prompt_id}%1"),
        ],
        [
            InlineKeyboardButton(text="⬅️ назад", callback_data=f"user_prompts%{user_id}"),
        ]
    ]

    try:
        await callback.message.edit_text(
            f"название: `{prompt_name}`\n"
            f"id: `{prompt_id}`\n"
            f"url: `t.me/{BOT_USERNAME}?start=prompt-{user_id}-{prompt_id}`\n"
            f"отправка: `{prompt_f_t}`\n"
            f"статус: `{prompt_pub_t}`\n",
            reply_markup=InlineKeyboardMarkup(inline_keyboard=buttons),
        )
    except:
        pass
    await callback.answer()



@router.callback_query(F.data.startswith("user_prompts%"))
async def user_prompts_callback(callback: CallbackQuery, dataalo=""):
    current_user_id = str(callback.from_user.id)
    if dataalo != "":
        data = dataalo
    else:
        data = callback.data

    data = data.split("%", 1)
    
    user_id = data[1]
    if user_id == current_user_id:
        config = get_user_config(user_id)
        prompt = config.get("prompt", "")
        prompts = config.get("prompts", {})

        buttons = []
        i = 0
        
        for name in prompts:
            alo = name
            name = prompts[name].get("name") + " (" + alo[:4] + ")"
            i += 1
            text = name
            if prompt == alo:
                text += " ✅"

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

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

        buttons.append(
            [
                InlineKeyboardButton(text="⬅️ назад", callback_data=f"prompts%{user_id}"),
                InlineKeyboardButton(text="📝 создать", callback_data=f"create%{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("p_cancel%"))
async def cancel_prompt_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:
        return await callback.answer("pashol naxxuy. иди наxuy.")

    alo_command[int(user_id)] = {"action": None, "chat_id": callback.message.chat.id, "message_id": callback.message.message_id}

    await user_prompts_callback(callback, dataalo=f"user_prompts%{user_id}")


@router.callback_query(F.data.startswith("vt%"))
async def view_text_callback(callback: CallbackQuery, dataalo=""):
    current_user_id = str(callback.from_user.id)
    if dataalo != "":
        data = dataalo
    else:
        data = callback.data

    data = data.split("%", 2)
        
    user_id = data[1]
    prompt_id = data[2]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return

    config = get_user_config(user_id)
    
    prompts = config["prompts"]

    prompt = prompts.get(prompt_id)
    

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

    await callback.message.edit_text(
        f"текст промпта `{prompt['name']}`:\n```prompt\n{prompt['text'][:3980]}\n```",
        reply_markup=InlineKeyboardMarkup(inline_keyboard=buttons),
    )


@router.callback_query(F.data.startswith("dp%"))
async def delete_prompt_callback(callback: CallbackQuery, dataalo=""):
    current_user_id = str(callback.from_user.id)
    if dataalo != "":
        data = dataalo
    else:
        data = callback.data

    data = data.split("%", 2)
        
    user_id = data[1]
    prompt_id = data[2]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return

    config = get_user_config(user_id)
    
    prompts = config["prompts"]

    del prompts[prompt_id]
    
    new_prompts = prompts
        
    set_user_config(
        user_id, 
        config.get("model"), 
        config.get("stream"), 
        config.get("call"), 
        DEFAULT_PROMPT,
        config.get("notify"),
        config.get("markdown"),
        new_prompts
    )

    return await user_prompts_callback(callback, dataalo=f"0%{user_id}")


@router.callback_query(F.data.startswith("edf%"))
async def edit_filer_callback(callback: CallbackQuery, dataalo=""):
    current_user_id = str(callback.from_user.id)
    if dataalo != "":
        data = dataalo
    else:
        data = callback.data

    data = data.split("%", 2)
        
    user_id = data[1]
    prompt_id = data[2]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return

    config = get_user_config(user_id)
    
    prompts = config["prompts"]

    prompt = prompts.get(prompt_id)

    if prompt["filer"]:
        prompt["filer"] = False
    else:
        prompt["filer"] = True
    
    new_prompts = prompts | {prompt_id: prompt}
        
    set_user_config(
        user_id, 
        config.get("model"), 
        config.get("stream"), 
        config.get("call"), 
        config.get("prompt"),
        config.get("notify"),
        config.get("markdown"),
        new_prompts
    )

    return await view_prompt_callback(callback, dataalo=f"0%{user_id}%{prompt_id}")

@router.callback_query(F.data.startswith("eds%"))
async def edit_status_callback(callback: CallbackQuery, dataalo=""):
    current_user_id = str(callback.from_user.id)
    if dataalo != "":
        data = dataalo
    else:
        data = callback.data

    data = data.split("%", 2)
        
    user_id = data[1]
    prompt_id = data[2]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return

    config = get_user_config(user_id)
    
    prompts = config["prompts"]

    prompt = prompts.get(prompt_id)

    if prompt["public"]:
        prompt["public"] = False
    else:
        prompt["public"] = True
    
    new_prompts = prompts | {prompt_id: prompt}
        
    set_user_config(
        user_id, 
        config.get("model"), 
        config.get("stream"), 
        config.get("call"), 
        config.get("prompt"),
        config.get("notify"),
        config.get("markdown"),
        new_prompts
    )

    return await view_prompt_callback(callback, dataalo=f"0%{user_id}%{prompt_id}")


@router.callback_query(F.data.startswith("edn%"))
async def edit_prompt_name_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 2)
    user_id = data[1]
    prompt_id = data[2]
    if user_id != current_user_id:
        return await callback.answer("pashol naxxuy. иди наxuy.")

    config = get_user_config(user_id)

    buttons = [
        [
            InlineKeyboardButton(
                text="❌ отменить", callback_data=f"p_cancel%{user_id}"
            )
        ]
    ]

    alo_command[int(user_id)] = {"action": "p_e_name", "chat_id": callback.message.chat.id, "message_id": callback.message.message_id, "prompt_id": prompt_id}

    await callback.message.edit_text(
        "установи новое название:",
        reply_markup=InlineKeyboardMarkup(inline_keyboard=buttons),
    )


@router.callback_query(F.data.startswith("edp%"))
async def edit_prompt_prompt_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 2)
    user_id = data[1]
    prompt_id = data[2]
    if user_id != current_user_id:
        return await callback.answer("pashol naxxuy. иди наxuy.")

    config = get_user_config(user_id)

    buttons = [
        [
            InlineKeyboardButton(
                text="❌ отменить", callback_data=f"p_cancel%{user_id}"
            )
        ]
    ]

    alo_command[int(user_id)] = {"action": "p_e_prompt", "chat_id": callback.message.chat.id, "message_id": callback.message.message_id, "prompt_id": prompt_id}

    await callback.message.edit_text(
        "установи новый промпт:",
        reply_markup=InlineKeyboardMarkup(inline_keyboard=buttons),
    )


@router.callback_query(F.data.startswith("ed%"))
async def edit_prompt_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 2)
    user_id = data[1]
    prompt_id = data[2]
    if user_id != current_user_id:
        return await callback.answer("pashol naxxuy. иди наxuy.")

    config = get_user_config(user_id)

    buttons = [
        [
            InlineKeyboardButton(
                text="💬 промпт", callback_data=f"edp%{user_id}%{prompt_id}"
            ),
            InlineKeyboardButton(
                text="📝 название", callback_data=f"edn%{user_id}%{prompt_id}"
            ),
        ],
        [
            InlineKeyboardButton(
                text="⬅️ назад", callback_data=f"vp%{user_id}%{prompt_id}"
            ),
        ]
    ]

    alo_command[int(user_id)] = {"action": "p_e_name", "chat_id": callback.message.chat.id, "message_id": callback.message.message_id, "prompt_id": prompt_id}

    await callback.message.edit_text(
        "установи новый промпт:",
        reply_markup=InlineKeyboardMarkup(inline_keyboard=buttons),
    )


@router.callback_query(F.data.startswith("create%"))
async def create_prompt_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:
        return await callback.answer("pashol naxxuy. иди наxuy.")

    config = get_user_config(user_id)
    if len(config["prompts"]) >= MAX_PROMPTS:
        return await callback.answer("ты превысил максимальное количество промптов!!!")

    buttons = [
        [
            InlineKeyboardButton(
                text="❌ отменить", callback_data=f"p_cancel%{user_id}"
            )
        ]
    ]

    alo_command[int(user_id)] = {"action": "p_name", "chat_id": callback.message.chat.id, "message_id": callback.message.message_id}

    await callback.message.edit_text(
        "установи отображаемое имя промпта:",
        reply_markup=InlineKeyboardMarkup(inline_keyboard=buttons),
    )


@router.callback_query(F.data.startswith("system_prompts%"))
async def system_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:
            alo = name
            name = SYSTEM_PROMPTS[name].get("name")
            i += 1
            text = name
            if prompt == alo:
                text += " ✅"

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

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

        buttons.append(
            [
                InlineKeyboardButton(text="⬅️ назад", callback_data=f"prompts%{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("sp%"))
async def set_prompt_callback(callback: CallbackQuery):
    # КАЛбек: sp%айди%промпт_айди%промпт%тип
    # 0 - answer + настройки
    # 1 - answer + открыть prompt view
    # 2 - answer
    # 3 - answer + открыть system prompt view
    
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 4)
    user_id = data[1]
    prompt_user_id = int(data[2])
    msg_type = 0
    new_status = data[3]
    
    if len(data) == 5:
        msg_type = int(data[4])
        
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return

    
            
    config = get_user_config(user_id)

    if prompt_user_id != 0:
        if len(config["prompts"]) >= MAX_PROMPTS:
            return await callback.answer("достигнуто максимальное количество промптов врат")
        else:
            await add_prompt_callback(callback, f"0%{user_id}%{prompt_user_id}%{data[3]}", alo=False)
    
    set_user_config(
        user_id, 
        config.get("model"), 
        config.get("stream"), 
        config.get("call"), 
        new_status, 
        config.get("notify"),
        config.get("markdown"),
        get_user_config(user_id).get("prompts")
    )
    if msg_type == 0:
        await callback.answer("da поменял на " + new_status)
        await settings_handler(callback)
    elif msg_type == 1:
        await callback.answer("установил промпт " + new_status)
        await view_prompt_callback(callback, dataalo=f"0%{user_id}%{new_status}")
    elif msg_type == 2:
        await callback.answer("установил " + new_status)
    elif msg_type == 3:
        await callback.answer("установил промпт " + new_status)
        await view_system_prompt_callback(callback, dataalo=f"0%{user_id}%{new_status}")


@router.callback_query(F.data.startswith("ap%"))
async def add_prompt_callback(callback: CallbackQuery, dataalo="", alo=True):
    current_user_id = str(callback.from_user.id)
    if dataalo != "":
        data = dataalo
    else:
        data = callback.data

    data = data.split("%", 3)
        
    user_id = data[1]
    prompt_user_id = int(data[2])
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return

    if prompt_user_id == 0:
        return await callback.answer("это стандартный промпт suka.")

    config = get_user_config(user_id)

    if len(config["prompts"]) >= MAX_PROMPTS:
        return await callback.answer("достигнуто максимальное количество промптов врат")
    
    new_prompts = config["prompts"]

    prompt = get_user_config(prompt_user_id)["prompts"].get(data[3], {})
    if not prompt:
        return await callback.answer("pashol naxxuy промпта нет")
    prompt_pub = prompt.get("public", False)
    if not prompt_pub: 
        return await callback.answer("pashol naxxuy промпт стал приватным")
    new_prompt = prompt
    new_prompt["public"] = False
    new_prompts = new_prompts | {data[3]: new_prompt}
        
    set_user_config(
        user_id, 
        config.get("model"), 
        config.get("stream"), 
        config.get("call"), 
        config.get("prompt"),
        config.get("notify"),
        config.get("markdown"),
        new_prompts
    )
    if alo:
        return await callback.answer("добавил твой промпт da.")


@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%"))
async def set_setting_callback(callback: CallbackQuery):
    current_user_id = str(callback.from_user.id)
    data = callback.data.split("%", 3)
    user_id = data[2]
    if user_id != current_user_id:
        await callback.answer("нет, не трогай это не твое")
        return

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

    config = get_user_config(user_id)

    alo = {
        data[1]: new_status
    }
    
    set_user_setting(
        user_id, 
        **alo
    )
    await settings_handler(callback)


@router.callback_query(F.data.startswith("new_md%"))
async def set_markdown_callback(callback: CallbackQuery, message=None):
    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",
        config.get("prompts")
    )
    if message:
        await message.delete()
    await callback.answer("выбран новый стиль!!")
    await callback.message.delete()


@router.callback_query(F.data.startswith("old_md%"))
async def set_markdown_callback(callback: CallbackQuery, message=None):
    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",
        config.get("prompts")
    )
    if message:
        await message.delete()
    await callback.answer("выбран старый стиль!!")
    await callback.message.delete()


@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()
