"""
actions/text_sender.py

Universal Text Sender
(Internal Flood Handling Version)
"""

from typing import Union
import asyncio

from pyrogram.errors import (
    FloodWait,
    RPCError,
    PeerIdInvalid,
    UsernameInvalid
)

from ..core.safe_executor import SafeExecutor
from ..core.delay_engine import DelayEngine
from ..core.logger import get_action_logger


class TextSender:

    # ==================================================
    def __init__(
        self,
        client,
        session_name: str
    ):

        self.client = client
        self.session_name = session_name

        self.logger = get_action_logger(
            action="text_sender",
            session=session_name
        )

    # ==================================================
    # INTERNAL FLOOD HANDLER
    # ==================================================

    async def _handle_flood(self, e: FloodWait):

        wait_time = int(e.value)

        self.logger.warning(
            f"[{self.session_name}] "
            f"FloodWait → {wait_time}s"
        )

        await asyncio.sleep(wait_time)

        self.logger.info(
            f"[{self.session_name}] "
            f"FloodWait finished"
        )

    # ==================================================
    async def _send_exec(
        self,
        target: Union[str, int],
        text: str,
        silent: bool
    ):

        return await self.client.send_message(
            chat_id=target,
            text=text,
            disable_notification=silent
        )

    # ==================================================
    async def send(
        self,
        target: Union[str, int],
        text: str,
        silent: bool = True,
        use_delay: bool = True
    ) -> bool:
        """
        Send text message safely
        """

        try:

            # ---------- VALIDATION ----------
            if not text.strip():

                self.logger.warning(
                    f"[{self.session_name}] "
                    f"Attempted empty text send"
                )

                return False

            # ---------- DELAY ----------
            if use_delay:

                await DelayEngine.text_delay()

            # ---------- EXEC ----------
            await SafeExecutor.run(

                self._send_exec(
                    target,
                    text,
                    silent
                ),

                session_name=self.session_name,
                action_name="send_text"
            )

            # ---------- LOG ----------
            self.logger.info(
                f"[{self.session_name}] "
                f"Text sent → {target} "
                f"(len={len(text)})"
            )

            return True

        # ==================================================
        # FLOOD
        # ==================================================
        except FloodWait as e:

            await self._handle_flood(e)
            return False

        # ==================================================
        # INVALID TARGET
        # ==================================================
        except (
            PeerIdInvalid,
            UsernameInvalid
        ):

            self.logger.error(
                f"[{self.session_name}] "
                f"Invalid target → {target}"
            )

            return False

        # ==================================================
        # RPC ERROR
        # ==================================================
        except RPCError as e:

            self.logger.error(
                f"[{self.session_name}] "
                f"RPC Error → {e}"
            )

            return False

        # ==================================================
        # GENERIC
        # ==================================================
        except Exception as e:

            self.logger.exception(
                f"[{self.session_name}] "
                f"Send text failed → {e}"
            )

            return False