# retoor <retoor@molodetz.nl>

import time
from collections import OrderedDict


class TTLCache:
    def __init__(self, ttl: int, max_size: int = 0):
        self.ttl = ttl
        self.max_size = max_size
        self._store = OrderedDict()

    def get(self, key: str):
        entry = self._store.get(key)
        if entry is None:
            return None
        value, expiry = entry
        if time.time() >= expiry:
            self._store.pop(key, None)
            return None
        self._store.move_to_end(key)
        return value

    def set(self, key: str, value) -> None:
        self._store[key] = (value, time.time() + self.ttl)
        self._store.move_to_end(key)
        if self.max_size and len(self._store) > self.max_size:
            self._store.popitem(last=False)

    def pop(self, key: str) -> None:
        self._store.pop(key, None)

    def clear(self) -> None:
        self._store.clear()

    def items(self) -> list:
        now = time.time()
        return [
            (key, value) for key, (value, expiry) in self._store.items() if now < expiry
        ]
