"""
Change profile photo via replied image
Downloads → saves → dispatches to sessions
"""

import os
import uuid

from pyrogram.types import Message

from remottxrea.actions.change_profile_picture import (
    ProfilePhotoChanger
)

from remottxrea.core.delay_engine import delay_engine


# =========================================
# CONFIG
# =========================================
DOWNLOAD_DIR = "downloads/profile_photos"
os.makedirs(DOWNLOAD_DIR, exist_ok=True)


class ChangePhotoHandler:

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

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

        # ---------- VALIDATION ----------
        if not message.reply_to_message:
            return await message.reply_text(
                "Reply to a photo"
            )

        reply = message.reply_to_message

        if not reply.photo:
            return await message.reply_text(
                "No photo found in reply"
            )

        # ---------- UNIQUE FILE NAME ----------
        file_name = f"profile_{uuid.uuid4().hex}.jpg"

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

        if not path or not os.path.exists(path):
            return await message.reply_text(
                "Download failed"
            )

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

            try:
                changer = ProfilePhotoChanger(
                    app,
                    phone
                )

                await changer.upload(path)

                # optional delay per session
                await delay_engine.session_delay()

                return f"{phone} → Photo updated"

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

        # ---------- RUN ----------
        await self.runner.run_action(action)

        await message.reply_text(
            "✅ Profile photos updated"
        )
