"""کد یکبارمصرف برای انتقال امن session از Keycloak theme به frontend."""
from __future__ import annotations

import secrets
import time
from threading import Lock
from typing import Any


class HandoffStore:
    def __init__(self, ttl_seconds: int = 120) -> None:
        self._data: dict[str, tuple[dict[str, Any], float]] = {}
        self._ttl = ttl_seconds
        self._lock = Lock()

    def _prune_locked(self) -> None:
        now = time.time()
        expired = [key for key, (_, exp) in self._data.items() if exp < now]
        for key in expired:
            self._data.pop(key, None)

    def create(self, session: dict[str, Any]) -> str:
        code = secrets.token_urlsafe(32)
        with self._lock:
            self._prune_locked()
            self._data[code] = (session, time.time() + self._ttl)
        return code

    def pop(self, code: str) -> dict[str, Any] | None:
        with self._lock:
            self._prune_locked()
            item = self._data.pop(code, None)
            return item[0] if item else None


handoff_store = HandoffStore()
