"""Queue (first in, first out) built from two stacks.

Idea
----
``list.pop(0)`` is O(n), so a naive list queue is slow. In practice use
``collections.deque``. This module shows a classic interview construction:
push onto an ``inbox`` stack; when you need the front, and the ``outbox`` is
empty, pour the whole inbox into the outbox (which reverses it). Each element
moves at most twice, so every operation is amortised O(1).

Complexity
----------
enqueue: O(1); dequeue / peek: O(1) amortised
Space: O(n)
"""

from typing import Generic, TypeVar

T = TypeVar("T")


class Queue(Generic[T]):
    def __init__(self) -> None:
        self._inbox: list[T] = []
        self._outbox: list[T] = []

    def enqueue(self, item: T) -> None:
        self._inbox.append(item)

    def _refill(self) -> None:
        if not self._outbox:
            while self._inbox:
                self._outbox.append(self._inbox.pop())
        if not self._outbox:
            raise IndexError("queue is empty")

    def dequeue(self) -> T:
        self._refill()
        return self._outbox.pop()

    def peek(self) -> T:
        self._refill()
        return self._outbox[-1]

    def __len__(self) -> int:
        return len(self._inbox) + len(self._outbox)
