import os
from django.core.management.base import BaseCommand
import telegram
from asgiref.sync import async_to_sync
from django.urls import reverse

class Command(BaseCommand):
    help = 'Sets webhook for Telegram setting'

    async def handle_async(self, *args, **options):
        WEBHOOK_HOST = os.getenv('WEBHOOK_URL')
        TELEGRAM_BOT_TOKEN = os.getenv('BOT_TOKEN')
        WEBHOOK_PORT = int(os.getenv('WEBHOOK_PORT'))
        bot = telegram.Bot(token=TELEGRAM_BOT_TOKEN)
        webhook_url = f"{WEBHOOK_HOST.rstrip('/')}{reverse('bot:webhook',kwargs={'token':TELEGRAM_BOT_TOKEN})}"
        self.stdout.write(self.style.WARNING(f'webhook url: {webhook_url}'))
        await bot.delete_webhook()
        await bot.set_webhook(webhook_url)

        self.stdout.write(self.style.SUCCESS(f'Webhook set to: {webhook_url}'))

        os.system(f'uvicorn --host 0.0.0.0 --port {WEBHOOK_PORT} --workers 1 --log-level info core.asgi:application')

    def handle(self, *args, **options):
        return async_to_sync(self.handle_async)(*args, **options)
