from pyrogram.errors import FloodWait
import asyncio

from ..core.safe_executor import SafeExecutor
from ..core.delay_engine import delay_engine
from ..core.logger import get_action_logger


class ProfilePhotoChanger:

    def __init__(self, client, session):
        self.client = client
        self.session = session
        self.log = get_action_logger(
            "profile_photo",
            session
        )

    async def _exec(self, path):
        await self.client.set_profile_photo(
            photo=path
        )

    async def upload(self, file_path):

        try:

            await delay_engine.change_profile()

            await SafeExecutor.run(
                self._exec(file_path),
                self.session,
                "profile_photo"
            )

            self.log.info(
                f"Photo updated → {file_path}"
            )

            return True

        except FloodWait as e:

            wait_time = int(e.value)
            self.log.warning(
                f"FloodWait → {wait_time}s"
            )

            await asyncio.sleep(wait_time)

            # یک بار retry
            try:
                await SafeExecutor.run(
                    self._exec(file_path),
                    self.session,
                    "profile_photo_retry"
                )

                self.log.info(
                    f"Photo updated after retry → {file_path}"
                )

                return True

            except Exception as retry_error:
                self.log.exception(retry_error)

        except Exception as e:
            self.log.exception(e)

        return False