import random
import time
from collections import defaultdict


class SmartDelayRandomizer:

    def __init__(self):

        # آخرین فعالیت اکانت
        self.last_activity = defaultdict(float)

        # تعداد تسک پشت سر هم
        self.activity_streak = defaultdict(int)

        # سقف جهانی
        self.MAX_DELAY = 200

        # ===== BASE DELAYS =====
        self.base_delays = {

            "send_message": (2, 6),
            "forward": (3, 8),
            "join_channel": (10, 25),
            "add_member": (15, 35),
            "view": (1, 3),

            "default": (3, 7)
        }

    # ---------- GET BASE ----------
    def _base_delay(self, method):

        return self.base_delays.get(
            method,
            self.base_delays["default"]
        )

    # ---------- FATIGUE ----------
    def _fatigue_delay(self, account):

        streak = self.activity_streak[account]

        if streak < 5:
            return 0

        if streak < 15:
            return random.uniform(2, 6)

        if streak < 30:
            return random.uniform(5, 15)

        if streak < 60:
            return random.uniform(10, 30)

        return random.uniform(20, 60)

    # ---------- MAIN ----------
    def get_delay(self, account, method):

        now = time.time()

        base_min, base_max = self._base_delay(method)

        base_delay = random.uniform(
            base_min,
            base_max
        )

        fatigue = self._fatigue_delay(account)

        delay = base_delay + fatigue

        # سقف 200 ثانیه
        delay = min(delay, self.MAX_DELAY)

        # آپدیت استریک
        if now - self.last_activity[account] < 60:
            self.activity_streak[account] += 1
        else:
            self.activity_streak[account] = 1

        self.last_activity[account] = now

        return round(delay, 2)


# ---------- GLOBAL INSTANCE ----------
delay_randomizer = SmartDelayRandomizer()
