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

SELECT_CHANNEL, MANAGE_BUTTONS = range(2)

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

async def select_channel(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    channel_id = int(query.data)
    context.user_data['channel_id'] = channel_id
    session = SessionLocal()
    buttons = session.query(Button).filter_by(channel_id=channel_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

channel_buttons_conv = ConversationHandler(
    entry_points=[CommandHandler('channel_buttons', channel_buttons_start)],
    states={
        SELECT_CHANNEL: [CallbackQueryHandler(select_channel)],
    },
    fallbacks=[]
)
