"""In-memory nonce store with TTL for replay protection."""

from __future__ import annotations

import secrets
import time
import threading


_DEFAULT_TTL = 600  # 10 minutes


class NonceStore:
    """Thread-safe in-memory nonce store with automatic expiry."""

    def __init__(self, ttl: int = _DEFAULT_TTL):
        self._ttl = ttl
        self._used: dict[str, float] = {}
        self._lock = threading.Lock()

    def generate(self) -> str:
        return f"n_{secrets.token_urlsafe(16)}"

    def mark_used(self, nonce: str) -> bool:
        """Mark a nonce as used. Returns False if already used (replay)."""
        self._cleanup()
        with self._lock:
            if nonce in self._used:
                return False
            self._used[nonce] = time.monotonic()
            return True

    def _cleanup(self):
        cutoff = time.monotonic() - self._ttl
        with self._lock:
            expired = [k for k, v in self._used.items() if v < cutoff]
            for k in expired:
                del self._used[k]
