"""Rate limiting middleware."""
from __future__ import annotations

import logging
import time
from collections import defaultdict

from telegram import Update
from telegram.ext import ContextTypes

from bot.constants import MSG

logger = logging.getLogger(__name__)

_user_times: dict[int, list[float]] = defaultdict(list)


def register(app) -> None:
    from telegram.ext import MessageHandler, filters

    app.add_handler(MessageHandler(filters.ALL & ~filters.COMMAND, rate_limit), group=-10)


async def rate_limit(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user = update.effective_user
    if not user:
        return
    uid = user.id
    now = time.time()
    times = _user_times[uid]
    # Clean old entries
    cutoff = now - 60
    _user_times[uid] = [t for t in times if t > cutoff]

    from bot.config import RATE_LIMIT_PER_SEC, RATE_LIMIT_PER_MIN

    recent_sec = [t for t in _user_times[uid] if now - t < 1]
    recent_min = _user_times[uid]

    if len(recent_sec) > RATE_LIMIT_PER_SEC or len(recent_min) > RATE_LIMIT_PER_MIN:
        # Check if message exists before replying
        msg = update.effective_message
        if msg:
            try:
                await msg.reply_text(MSG["wait"])
            except Exception as e:
                logger.warning("Rate-limit reply failed: %s", e)
        return

    _user_times[uid].append(now)
