"""
core/safe_executor.py

Unified execution wrapper
Flood + RPC + Retry + Logging
"""

from pyrogram.errors import (
    FloodWait,
    RPCError
)

from ..core.logger import get_action_logger
from ..core.flood_handler import FloodHandler
from ..core.rpc_handler import RPCHandler
from ..core.retry_handler import RetryHandler


class SafeExecutor:

    @staticmethod
    async def run(
        coro,
        session_name: str,
        action_name: str,
        use_retry: bool = True
    ):

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

        try:

            logger.info(
                f"Executing → {action_name}"
            )

            if use_retry:

                result = await RetryHandler.retry(
                    coro,
                    session_name,
                    action_name
                )

            else:
                result = await coro

            logger.info(
                f"Success → {action_name}"
            )

            return result

        # ---------- FLOOD ----------
        except FloodWait as e:

            logger.warning(
                f"Flood in executor → "
                f"{action_name}"
            )

            await FloodHandler.handle(
                e,
                session_name,
                action_name
            )

            return False

        # ---------- RPC ----------
        except RPCError as e:

            await RPCHandler.handle(
                e,
                session_name,
                action_name
            )

            return False

        # ---------- GENERIC ----------
        except Exception as e:

            logger.exception(
                f"Unhandled error → "
                f"{action_name} | {e}"
            )

            return False
