import logging
import os
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackQueryHandler, ConversationHandler, ContextTypes
from dotenv import load_dotenv
from db import SessionLocal, init_db
from models import Admin, Channel, Group, Button

load_dotenv()
TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

init_db()

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    session = SessionLocal()
    user_id = update.effective_user.id
    admin = session.query(Admin).filter_by(tg_id=user_id).first()
    if not admin:
        admin = Admin(tg_id=user_id)
        session.add(admin)
        session.commit()
        await update.message.reply_text('Вы зарегистрированы как админ.')
    else:
        await update.message.reply_text('Вы уже зарегистрированы.')
    session.close()


# Импорт обработчиков
from handlers.add_channel import add_channel
from handlers.add_group import add_group
from handlers.add_button import add_button_conv
from handlers.new_post import new_post_conv
from handlers.group_buttons import group_buttons_conv
from handlers.channel_buttons import channel_buttons_conv
from handlers.edit_button import edit_button
from handlers.del_button import del_button

def main():

    application = Application.builder().token(TELEGRAM_TOKEN).build()
    application.add_handler(CommandHandler('start', start))
    application.add_handler(CommandHandler('add_channel', add_channel))
    application.add_handler(CommandHandler('add_group', add_group))
    application.add_handler(add_button_conv)
    application.add_handler(new_post_conv)
    application.add_handler(group_buttons_conv)
    application.add_handler(channel_buttons_conv)
    application.add_handler(CommandHandler('edit_button', edit_button))
    application.add_handler(CommandHandler('del_button', del_button))
    application.run_polling()

if __name__ == '__main__':
    main()
