# bot/management/commands/runbot.py
from django.core.management.base import BaseCommand, CommandError
from bot.utils import create_bot_instance
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, CallbackQueryHandler
from bot.handlers import whoami, show_all_invoices_callback, handle_client_card
from bot.chat import ChatHandler
from bot.welcome import WelcomeHandler
class Command(BaseCommand):
    help = 'Запускает Telegram-бота'

    def handle(self, *args, **options):
        try:
            bot = create_bot_instance()
        except Exception as e:
            raise CommandError(f"Ошибка при создании бота: {e}")

        application = ApplicationBuilder().token(bot.token).build()

        async def start_command(update, context):
            await update.message.reply_text("Здравствуйте! Используйте команду /bind для привязки клиентской карты.")

        welcome_handler = WelcomeHandler(bot=application.bot)
        application.add_handler(CommandHandler("start", welcome_handler.send_welcome))
        application.add_handler(CommandHandler("bind", handle_client_card))
        application.add_handler(CommandHandler("whoami", whoami))
        application.add_handler(CallbackQueryHandler(show_all_invoices_callback, pattern="^show_all_invoices$"))
        
        chat_handler = ChatHandler(bot=application.bot)
        application.add_handler(MessageHandler(filters.TEXT | filters.PHOTO, chat_handler.handle_chat_message))

        self.stdout.write("Бот запущен. Ожидание обновлений...")
        application.run_polling()
        self.stdout.write("Бот остановлен.")
