from telegram import Update
from telegram.ext import ContextTypes, ConversationHandler
from db import SessionLocal
from models import Channel, Group, Button

SELECT_TARGET, INPUT_NAME, INPUT_URL = range(3)

async def add_button_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    session = SessionLocal()
    channels = session.query(Channel).all()
    groups = session.query(Group).all()
    session.close()
    keyboard = []
    for c in channels:
        keyboard.append([{'text': f'Канал: {c.name}', 'callback_data': f'channel_{c.id}'}])
    for g in groups:
        keyboard.append([{'text': f'Группа: {g.name}', 'callback_data': f'group_{g.id}'}])
    if not keyboard:
        await update.message.reply_text('Нет каналов или групп для добавления кнопки.')
        return ConversationHandler.END
    await update.message.reply_text('Выберите канал или группу:', reply_markup=None)
    context.user_data['keyboard'] = keyboard
    return SELECT_TARGET

async def select_target(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    data = query.data
    context.user_data['target'] = data
    await query.edit_message_text('Введите название кнопки:')
    return INPUT_NAME

async def input_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.user_data['button_name'] = update.message.text
    await update.message.reply_text('Введите ссылку для кнопки:')
    return INPUT_URL

async def input_url(update: Update, context: ContextTypes.DEFAULT_TYPE):
    url = update.message.text
    name = context.user_data['button_name']
    target = context.user_data['target']
    session = SessionLocal()
    if target.startswith('channel_'):
        channel_id = int(target.split('_')[1])
        button = Button(name=name, url=url, channel_id=channel_id)
    else:
        group_id = int(target.split('_')[1])
        button = Button(name=name, url=url, group_id=group_id)
    session.add(button)
    session.commit()
    session.close()
    await update.message.reply_text('Кнопка добавлена.')
    return ConversationHandler.END

add_button_conv = ConversationHandler(
    entry_points=[CommandHandler('add_button', add_button_start)],
    states={
        SELECT_TARGET: [CallbackQueryHandler(select_target)],
        INPUT_NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_name)],
        INPUT_URL: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_url)],
    },
    fallbacks=[]
)
