"""
actions/text_sender.py

Universal Text Sender

Supports:
- Username
- Chat ID
- Invite link
- Silent send
- Multi-line text

Integrated with:
- SafeExecutor
- DelayEngine
- FloodHandler
- Central Logger
"""

from typing import Union

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

from core.safe_executor import (
    SafeExecutor
)

from core.delay_engine import (
    DelayEngine
)

from core.flood_handler import (
    FloodHandler
)

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
        )

    # ==================================================
    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

        Args:
            target:
                username / id / link

            text:
                message content

            silent:
                disable notification

            use_delay:
                apply delay engine
        """

        try:

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

                self.logger.warning(
                    "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"Text sent → {target} "
                f"(len={len(text)})"
            )

            return True

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

            self.logger.warning(
                f"FloodWait → {e.value}s"
            )

            await FloodHandler.handle(
                e,
                session_name=self.session_name,
                action="send_text"
            )

            return False

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

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

            return False

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

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

            return False

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

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

            return False
