from pyrogram.errors import FloodWait, RPCError
import asyncio

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


class BioChanger:

    MAX_LENGTH = 70

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

    async def _exec(self, bio):
        await self.client.update_profile(bio=bio)

    async def change(self, bio: str):

        try:

            if len(bio) > self.MAX_LENGTH:
                raise ValueError("Bio too long")

            await delay_engine.change_profile()

            await SafeExecutor.run(
                self._exec(bio),
                self.session,
                "change_bio"
            )

            self.log.info(f"Bio updated → {bio}")
            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(bio),
                    self.session,
                    "change_bio_retry"
                )

                self.log.info(f"Bio updated after retry → {bio}")
                return True

            except Exception as retry_error:
                self.log.exception(f"Retry failed → {retry_error}")

        except RPCError as e:
            self.log.error(f"RPC → {e}")

        except Exception as e:
            self.log.exception(f"Error → {e}")

        return False