from datetime import datetime, timedelta
import asyncio

from pyrogram.errors import FloodWait

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


class AutoMuteManager:

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

    async def _exec(self, chat, hours):

        if hours is None:
            until = datetime.utcnow() + timedelta(days=3650)
        else:
            until = datetime.utcnow() + timedelta(hours=hours)

        await self.client.mute_chat(
            chat,
            until_date=until
        )

    async def mute(self, chat, hours=None):

        try:

            await delay_engine.join_delay()

            await SafeExecutor.run(
                self._exec(chat, hours),
                self.session,
                "mute"
            )

            self.log.info(f"Muted → {chat}")
            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(chat, hours),
                    self.session,
                    "mute_retry"
                )

                self.log.info(f"Muted after retry → {chat}")
                return True

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

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

        return False