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 NameChanger:

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

    async def _exec(self, first, last):
        await self.client.update_profile(
            first_name=first,
            last_name=last
        )

    async def change(
        self,
        first_name,
        last_name=""
    ):

        try:

            await delay_engine.change_profile()

            await SafeExecutor.run(
                self._exec(
                    first_name,
                    last_name
                ),
                self.session,
                "change_name"
            )

            self.log.info(
                f"Name → {first_name} {last_name}"
            )

            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(
                        first_name,
                        last_name
                    ),
                    self.session,
                    "change_name_retry"
                )

                self.log.info(
                    f"Name updated after retry → {first_name} {last_name}"
                )

                return True

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

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

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

        return False