"""
core/flood_handler.py

Handles FloodWait globally
Safe sleep + logging + escalation
"""

import asyncio
from datetime import datetime

from pyrogram.errors import FloodWait

from remottxrea.core.logger import get_action_logger


class FloodHandler:

    # حداقل و حداکثر wait ایمن
    MIN_WAIT = 5
    MAX_WAIT = 3600  # 1h cap

    @staticmethod
    async def handle(
        error: FloodWait,
        session_name: str,
        action: str
    ):

        logger = get_action_logger(
            action="flood_handler",
            session=session_name
        )

        wait_time = int(error.value)

        # Safety clamp
        wait_time = max(
            FloodHandler.MIN_WAIT,
            min(wait_time, FloodHandler.MAX_WAIT)
        )

        logger.warning(
            f"FloodWait detected | "
            f"Action={action} | "
            f"Wait={wait_time}s"
        )

        # Adaptive escalation log
        if wait_time > 300:
            logger.error(
                f"Severe Flood → {wait_time}s"
            )

        await asyncio.sleep(wait_time)

        logger.info(
            f"FloodWait finished | "
            f"Resume action={action}"
        )
