"""
Forward command dispatcher
forward <link> <target>

Supports:
- Public links
- Private links
- Single message
- Multiple IDs (optional future)
"""

from pyrogram.types import Message

from ...actions.forward_message import (
    ForwardManager
)

from ...core.delay_engine import delay_engine


class ForwardHandler:

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

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

        text = message.text.strip()

        # =========================================
        # PARSE COMMAND
        # =========================================
        try:
            _, link, target = text.split(
                " ",
                2
            )

        except ValueError:
            return await message.reply_text(
                "Usage:\nforward <link> <target>"
            )

        # =========================================
        # BASIC VALIDATION
        # =========================================
        if "t.me/" not in link:
            return await message.reply_text(
                "Invalid message link"
            )

        if not target:
            return await message.reply_text(
                "Invalid target"
            )

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

            try:

                manager = ForwardManager(
                    app,
                    phone
                )

                await manager.forward(
                    source=link,
                    message_ids=None,
                    target=target
                )

                # session delay
                await delay_engine.session_delay()

                return f"{phone} → Forwarded"

            except Exception as e:
                return f"{phone} → Error: {e}"

        # =========================================
        # DISPATCH
        # =========================================
        results = await self.runner.run_action(
            action
        )

        # =========================================
        # REPORT
        # =========================================
        success = sum(
            1 for r in results
            if "Forwarded" in str(r)
        )

        fail = len(results) - success

        await message.reply_text(
            f"✅ Forward done\n"
            f"Success: {success}\n"
            f"Failed: {fail}"
        )
