"""
Send media via reply
Downloads → dispatch → multi session send

Supports:
- Photo
- Video
- Document
- Audio
- Voice
- Animation (GIF)
- Auto media detection

Integrated:
- Logger
- DelayEngine
- FloodWait handler
"""

import os
import uuid
import asyncio

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

from remottxrea.actions.media_sender import (
    MediaSender
)

from remottxrea.core.logger import (
    get_action_logger
)

from remottxrea.core.delay_engine import (
    delay_engine
)


DOWNLOAD_DIR = "downloads/media"
os.makedirs(DOWNLOAD_DIR, exist_ok=True)


class SendMediaHandler:

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

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

        # ---------- REPLY CHECK ----------
        if not message.reply_to_message:
            return await message.reply_text(
                "Reply to media\n\nUsage:\nsendMedia <target>"
            )

        # ---------- TARGET ----------
        try:
            target = message.text.split(
                " ",
                1
            )[1]
        except IndexError:
            return await message.reply_text(
                "Usage:\nsendMedia <target>"
            )

        media_msg = message.reply_to_message

        # ---------- MEDIA DETECTION ----------
        media_type = self._detect_media_type(
            media_msg
        )

        if not media_type:
            return await message.reply_text(
                "Unsupported media type"
            )

        # ---------- UNIQUE FILE ----------
        file_name = (
            f"{uuid.uuid4()}"
        )

        path = await media_msg.download(
            file_name=os.path.join(
                DOWNLOAD_DIR,
                file_name
            )
        )

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

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

            sender = MediaSender(
                app,
                phone
            )

            try:

                # ---------- DELAY ----------
                await delay_engine.media_delay()

                # ---------- SEND ----------
                await sender.send(
                    chat_id=target,
                    file_path=path,
                    media_type=media_type,
                    silent=True
                )

                logger.info(
                    f"Media sent → {target} "
                    f"type={media_type}"
                )

                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 media error → {e}"
                )
                return False

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

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

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

    # =============================================
    # MEDIA TYPE DETECTOR
    # =============================================
    def _detect_media_type(
        self,
        msg: Message
    ) -> str | None:

        if msg.photo:
            return "photo"

        if msg.video:
            return "video"

        if msg.document:
            return "document"

        if msg.audio:
            return "audio"

        if msg.voice:
            return "voice"

        if msg.animation:
            return "animation"

        return None
