from __future__ import annotations

import threading
import time

_SESSIONS: dict[int, dict] = {}
_LOCK = threading.RLock()
_TTL_SECONDS = 1800


def set(chat_id: int, flow: str, step: str, **data) -> None:
    with _LOCK:
        _SESSIONS[chat_id] = {
            "flow": flow,
            "step": step,
            "data": data,
            "time": time.time(),
        }


def get(chat_id: int):
    with _LOCK:
        session = _SESSIONS.get(chat_id)
        if session and time.time() - session["time"] > _TTL_SECONDS:
            _SESSIONS.pop(chat_id, None)
            return None
        return session


def update(chat_id: int, step: str | None = None, **data) -> None:
    with _LOCK:
        session = get(chat_id)
        if not session:
            return
        if step:
            session["step"] = step
        session["data"].update(data)
        session["time"] = time.time()


def clear(chat_id: int) -> None:
    with _LOCK:
        _SESSIONS.pop(chat_id, None)
