import asyncio
import logging
from aiogram import Bot
from aiogram.types import InputRichMessage
from aiogram.exceptions import TelegramRetryAfter, TelegramForbiddenError, TelegramAPIError

logger = logging.getLogger(__name__)

async def safe_broadcast(
    bot: Bot, 
    user_ids: list[int], 
    text: str = None, 
    reply_markup=None, 
    parse_mode="HTML", 
    link_preview_options=None,
    report_admin_id: int = None,
    rich_message: InputRichMessage = None
):
    """
    Safely broadcasts a message to a list of users, handling Telegram's flood limits.
    """
    sent = 0
    failed = 0
    
    # Generate draft ID if report_admin_id is provided
    import random
    draft_id = random.randint(10000, 99999) if report_admin_id else None
    total_users = len(user_ids)
    
    for user_id in user_ids:
        try:
            if rich_message:
                await bot.send_rich_message(
                    chat_id=user_id,
                    rich_message=rich_message,
                    reply_markup=reply_markup
                )
            else:
                if rich_message:
                    await bot.send_rich_message(
                        chat_id=user_id,
                        rich_message=rich_message,
                        reply_markup=reply_markup
                    )
                else:
                    await bot.send_message(
                        chat_id=user_id,
                        text=text,
                        reply_markup=reply_markup,
                        parse_mode=parse_mode,
                        link_preview_options=link_preview_options
                    )
            sent += 1
        except TelegramRetryAfter as e:
            logger.warning(f"Flood limit exceeded. Sleeping for {e.retry_after} seconds.")
            await asyncio.sleep(e.retry_after)
            # Retry once after sleeping
            try:
                if rich_message:
                    await bot.send_rich_message(
                        chat_id=user_id,
                        rich_message=rich_message,
                        reply_markup=reply_markup
                    )
                else:
                    await bot.send_message(
                        chat_id=user_id,
                        text=text,
                        reply_markup=reply_markup,
                        parse_mode=parse_mode,
                        link_preview_options=link_preview_options
                    )
                sent += 1
            except Exception as retry_e:
                logger.error(f"Failed to send to {user_id} after retry: {retry_e}")
                failed += 1
        except TelegramForbiddenError:
            # User blocked the bot or account deleted
            failed += 1
        except TelegramAPIError as e:
            logger.error(f"API Error sending to {user_id}: {e}")
            failed += 1
        except Exception as e:
            logger.error(f"Unexpected error sending to {user_id}: {e}")
            failed += 1
            
        # Update progress draft to the admin (Rich Message Drafts)
        if report_admin_id and (sent + failed) % 5 == 0:
            progress_html = (
                f"<h1>📊 گزارش پیشرفت ارسال همگانی</h1>"
                f"<hr/>"
                f"<p>در حال ارسال پیام برای کاربران... لطفاً شکیبا باشید.</p>"
                f"<br/>"
                f"<table bordered striped>"
                f"  <tr><th>وضعیت</th><td>در حال ارسال ⏳</td></tr>"
                f"  <tr><th>کل کاربران هدف</th><td><b>{total_users}</b> نفر</td></tr>"
                f"  <tr><th>ارسال موفق</th><td><b>{sent}</b> نفر</td></tr>"
                f"  <tr><th>ناموفق</th><td><b>{failed}</b> نفر</td></tr>"
                f"</table>"
            )
            try:
                await bot.send_rich_message_draft(
                    chat_id=report_admin_id,
                    draft_id=draft_id,
                    rich_message=InputRichMessage(html=progress_html)
                )
            except Exception:
                pass
                
        # Global safe rate limit: 0.05s between messages = ~20 messages per second.
        # Telegram global limit is ~30 per second.
        await asyncio.sleep(0.05)
        
    if report_admin_id:
        report_html = (
            f"<h1>📊 گزارش نهایی ارسال همگانی</h1>"
            f"<hr/>"
            f"<p>عملیات ارسال همگانی با موفقیت به پایان رسید.</p>"
            f"<br/>"
            f"<table bordered striped>"
            f"  <tr><th>وضعیت</th><td>پایان یافته ✅</td></tr>"
            f"  <tr><th>کل کاربران هدف</th><td><b>{total_users}</b> نفر</td></tr>"
            f"  <tr><th>ارسال موفق</th><td><b>{sent}</b> نفر</td></tr>"
            f"  <tr><th>ناموفق (مسدود/حذف شده)</th><td><b>{failed}</b> نفر</td></tr>"
            f"</table>"
        )
        try:
            await bot.send_rich_message(
                chat_id=report_admin_id,
                rich_message=InputRichMessage(html=report_html)
            )
        except Exception:
            pass
            
    return sent, failed
