"""
Send text dispatcher
Command:

sendText <target> <text>

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

Integrated:
- Logger per session
- DelayEngine
- FloodWait handler
- RPC error handling
- Result aggregation
"""

import asyncio

from pyrogram.types import Message
from pyrogram.errors import FloodWait, RPCError

from remottxrea.actions.text_sender import (
    TextSender
)

from remottxrea.core.logger import (
    get_action_logger
)

from remottxrea.core.delay_engine import (
    delay_engine
)


class SendTextHandler:

    def __init__(self, runner):
        self.runner = runner

    # ==================================================
    async def handle(self, message: Message):

        text_raw = message.text.strip()

        # ---------------------------------
        # PARSE COMMAND
        # ---------------------------------
        try:

            _, target, text = text_raw.split(
                " ",
                2
            )

        except ValueError:

            return await message.reply_text(
                "Usage:\n"
                "sendText <target> <text>\n\n"
                "Example:\n"
                "sendText @telegram Hello world"
            )

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

            return await message.reply_text(
                "Text cannot be empty"
            )

        # ==================================================
        # ACTION FUNCTION
        # ==================================================
        async def action(phone, app):

            logger = get_action_logger(
                action="text_sender",
                session=phone
            )

            sender = TextSender(
                app,
                phone
            )

            try:

                logger.info(
                    f"Dispatch text → {target}"
                )

                # ---------- SAFE DELAY ----------
                await delay_engine.text_delay()

                # ---------- SEND ----------
                await sender.send(
                    target=target,
                    text=text,
                    silent=True
                )

                logger.info(
                    f"Text sent successfully "
                    f"(len={len(text)})"
                )

                return True

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

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

                await asyncio.sleep(
                    e.value
                )

                return False

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

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

                return False

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

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

                return False

        # ==================================================
        # RUN MULTI SESSION
        # ==================================================
        results = await self.runner.run_action(
            action
        )

        # اگر runner چیزی برنگرداند
        if results is None:
            return await message.reply_text(
                "Execution finished"
            )

        # ---------------------------------
        # SUMMARY
        # ---------------------------------
        success = sum(
            1 for r in results if r
        )
        failed = len(results) - success

        await message.reply_text(
            "Text Dispatch Completed\n\n"
            f"Success: {success}\n"
            f"Failed: {failed}"
        )
