from collections import deque
import random


class SongQueue:
    def __init__(self):
        self.items = []
        self.history = deque(maxlen=20)
        self.infinite_loop = False

    # ==========================
    # ADD
    # ==========================
    def add(self, song):
        self.items.append(song)
        print(f"[Queue] add → {getattr(song, 'title', 'Unknown')} (size={len(self.items)})")
        return len(self.items)

    # ==========================
    # REMOVE LAST (FIXED)
    # ==========================
    def pop_last(self):
        if not self.items:
            return None

        removed = self.items.pop()
        print(f"[Queue] pop_last → {getattr(removed, 'title', 'Unknown')}")
        return removed

    # ==========================
    # CURRENT
    # ==========================
    def current(self):
        if not self.items:
            return None
        return self.items[0]

    # ==========================
    # NEXT
    # ==========================
    def next(self):
        if not self.items:
            print("[Queue] next → empty")
            return None

        current = self.items[0]
        self.history.appendleft(current)

        if getattr(current, "loop_left", 0) > 0:
            current.loop_left -= 1
            print(f"[Queue] loop → {current.title} left={current.loop_left}")
            return current

        if self.infinite_loop:
            print(f"[Queue] infinite loop → {current.title}")
            return current

        self.items.pop(0)

        nxt = self.current()
        if nxt:
            print(f"[Queue] next → {nxt.title}")
        else:
            print("[Queue] queue finished")

        return nxt

    # ==========================
    # PREVIOUS
    # ==========================
    def previous(self):
        if not self.history:
            print("[Queue] previous → empty")
            return None

        prev = self.history.popleft()
        self.items.insert(0, prev)

        print(f"[Queue] previous → {prev.title}")
        return prev

    # ==========================
    # SHUFFLE
    # ==========================
    def shuffle(self):
        if len(self.items) <= 1:
            print("[Queue] shuffle skipped")
            return False

        current = self.items.pop(0)
        random.shuffle(self.items)
        self.items.insert(0, current)

        print("[Queue] shuffled")
        return True

    # ==========================
    # CLEAR
    # ==========================
    def clear(self):
        print("[Queue] cleared")
        self.items.clear()
        self.history.clear()
        self.infinite_loop = False
        
