from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import CommandHandler, CallbackQueryHandler, ConversationHandler, ContextTypes
from db import SessionLocal
from models import Group, Button

SELECT_GROUP, MANAGE_BUTTONS = range(2)

async def group_buttons_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    session = SessionLocal()
    groups = session.query(Group).all()
    session.close()
    keyboard = [[InlineKeyboardButton(g.name, callback_data=str(g.id))] for g in groups]
    await update.message.reply_text(
        "Выберите группу для настройки клавиатуры:",
        reply_markup=InlineKeyboardMarkup(keyboard)
    )
    return SELECT_GROUP

async def select_group(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    group_id = int(query.data)
    context.user_data['group_id'] = group_id
    session = SessionLocal()
    buttons = session.query(Button).filter_by(group_id=group_id).all()
    session.close()
    text = "Кнопки этой группы:\n"
    for b in buttons:
        text += f"- {b.name}: {b.url}\n"
    text += "\nДобавить новую кнопку: /add_button\nУдалить: /del_button <название>"
    await query.edit_message_text(text)
    return ConversationHandler.END

group_buttons_conv = ConversationHandler(
    entry_points=[CommandHandler('group_buttons', group_buttons_start)],
    states={
        SELECT_GROUP: [CallbackQueryHandler(select_group)],
    },
    fallbacks=[]
)
