from telegram import Update, InputMediaPhoto, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import ContextTypes, ConversationHandler, MessageHandler, CommandHandler, filters
from db import SessionLocal
from models import Channel, Group, Button

SELECT_MEDIA, SELECT_TEXT, SELECT_TARGET = range(3)

async def new_post_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text('Отправьте картинку для поста или /skip:')
    return SELECT_MEDIA

async def select_media(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.message.photo:
        context.user_data['photo'] = update.message.photo[-1].file_id
    await update.message.reply_text('Введите текст поста или пересланное сообщение:')
    return SELECT_TEXT

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

async def select_target(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    data = query.data
    session = SessionLocal()
    if data.startswith('channel_'):
        channel_id = int(data.split('_')[1])
        channel = session.query(Channel).get(channel_id)
        buttons = session.query(Button).filter_by(channel_id=channel_id).all()
        markup = InlineKeyboardMarkup([[InlineKeyboardButton(b.name, url=b.url)] for b in buttons]) if buttons else None
        await context.bot.send_photo(chat_id=channel.link, photo=context.user_data.get('photo'), caption=context.user_data.get('text'), reply_markup=markup)
    else:
        group_id = int(data.split('_')[1])
        group = session.query(Group).get(group_id)
        buttons = session.query(Button).filter_by(group_id=group_id).all()
        markup = InlineKeyboardMarkup([[InlineKeyboardButton(b.name, url=b.url)] for b in buttons]) if buttons else None
        await context.bot.send_photo(chat_id=group.link, photo=context.user_data.get('photo'), caption=context.user_data.get('text'), reply_markup=markup)
    session.close()
    await query.edit_message_text('Пост отправлен!')
    return ConversationHandler.END

new_post_conv = ConversationHandler(
    entry_points=[CommandHandler('new_post', new_post_start)],
    states={
        SELECT_MEDIA: [MessageHandler(filters.PHOTO | filters.Document.IMAGE | filters.COMMAND, select_media)],
        SELECT_TEXT: [MessageHandler(filters.TEXT | filters.FORWARDED, select_text)],
        SELECT_TARGET: [CallbackQueryHandler(select_target)],
    },
    fallbacks=[]
)
