"""Dataset lookup and caching."""

from __future__ import annotations

import time

from ragflow_sdk import RAGFlow


class DatasetLookup:
    """Bidirectional name<->id dataset cache with TTL and negative caching."""

    def __init__(self, ragflow: RAGFlow, ttl_seconds: int = 300):
        self._ragflow = ragflow
        self._ttl = ttl_seconds
        self._name_to_id: dict[str, tuple[float, str | None]] = {}
        self._id_to_name: dict[str, tuple[float, str | None]] = {}

    def invalidate(self) -> None:
        self._name_to_id.clear()
        self._id_to_name.clear()

    def _is_alive(self, ts: float) -> bool:
        return (time.time() - ts) < self._ttl

    def get_id(self, name: str) -> str | None:
        cached = self._name_to_id.get(name)
        if cached and self._is_alive(cached[0]):
            return cached[1]

        datasets = self._ragflow.list_datasets(name=name)
        dataset_id = datasets[0].id if datasets else None
        now = time.time()
        self._name_to_id[name] = (now, dataset_id)
        if dataset_id:
            self._id_to_name[dataset_id] = (now, name)
        return dataset_id

    def get_name(self, dataset_id: str) -> str | None:
        cached = self._id_to_name.get(dataset_id)
        if cached and self._is_alive(cached[0]):
            return cached[1]

        datasets = self._ragflow.list_datasets(id=dataset_id)
        name = datasets[0].name if datasets else None
        now = time.time()
        self._id_to_name[dataset_id] = (now, name)
        if name:
            self._name_to_id[name] = (now, dataset_id)
        return name
