import os

from celery import shared_task
import telegram
from time import sleep
from asgiref.sync import  sync_to_async
from bot.models import User
import asyncio
from functools import wraps
from django.conf import settings

def run_async(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        loop = asyncio.get_event_loop()
        return loop.run_until_complete(func(*args, **kwargs))
    return wrapper
@shared_task(queue='broadcast')
@run_async
async def broadcast_message_to_users(users_id,message_id,from_user_id,**kwargs):
    """
    Celery task to send message to all active users
    """
    bot = telegram.Bot(settings.TELEGRAM_BOT_TOKEN)
    success_count = 0
    failed_count = 0
    for user_id in users_id:
        try:
            await bot.copy_message(
                chat_id=user_id,
                from_chat_id=from_user_id,
                message_id=message_id,**kwargs
            )
            success_count += 1
        except telegram.error.Forbidden as e:
            print(e)
            await sync_to_async(User.objects.filter(user_id=user_id).update)(is_active=False)
            failed_count += 1
            continue
        except telegram.error.RetryAfter as e:
            print(e)

            retry_after=e.retry_after
            sleep(retry_after+5)
            await bot.copy_message(
                chat_id=user_id,
                from_chat_id=from_user_id,
                message_id=message_id, **kwargs
            )
        except Exception as e:
            print(e)
            failed_count += 1
            continue
        sleep(3)

    msg=f'''
        total_users: {len(users_id)}
        success_count: {success_count}
        failed_count: {failed_count}
    '''
    await bot.send_message(
        chat_id=int(os.getenv('ADMIN_IDS').split(' ')[0]),
        text=msg,
    )
