"""Admin broadcast: /broadcast <text> sends to all users."""
import asyncio
from telegram import Update
from telegram.ext import ContextTypes
from database.db import DB
from utils.decorators import admin_only
from services.notifications import notify_staff

@admin_only
async def broadcast(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if not context.args:
        await update.message.reply_text(
            "Usage: /broadcast <message>\n"
            "Tip: reply to a photo/video/document with /broadcast to forward it."); return
    text = update.message.text.split(" ", 1)[1]
    rows = await DB.fetchall("SELECT user_id FROM users WHERE is_banned=0")
    sent = delivered = failed = 0
    reply_target = update.message.reply_to_message
    for r in rows:
        sent += 1
        try:
            if reply_target:
                await reply_target.copy(chat_id=r["user_id"])
                if text:
                    await context.bot.send_message(r["user_id"], text)
            else:
                await context.bot.send_message(r["user_id"], text)
            delivered += 1
        except Exception:
            failed += 1
        # rate limit ~25 msg/sec to stay under Telegram limits
        if sent % 25 == 0:
            await asyncio.sleep(1)

    await DB.execute(
        "INSERT INTO broadcasts(admin_id, payload, sent, delivered, failed) VALUES (?,?,?,?,?)",
        (update.effective_user.id, text[:500], sent, delivered, failed))
    summary = f"📢 Broadcast done. Sent: {sent} · Delivered: {delivered} · Failed: {failed}"
    await update.message.reply_text(summary)
    await notify_staff(context.bot, summary)
