from __future__ import annotations

from collections import OrderedDict
from typing import Any

from exonware.xwquery.runtime.optimization import (
    InMemoryStatisticsManager,
    QueryPlanner,
    SimpleCostModel,
    OptimizationLevel,
)


class QueryCache:
    def __init__(self, max_size: int = 1000, use_xwnode: bool = True):
        self._max_size = max(1, int(max_size))
        self._use_xwnode = bool(use_xwnode)
        self._store: OrderedDict[str, Any] = OrderedDict()
        self._hits = 0
        self._misses = 0

    def put(self, key: str, value: Any) -> None:
        if key in self._store:
            self._store.pop(key)
        self._store[key] = value
        while len(self._store) > self._max_size:
            self._store.popitem(last=False)

    def get(self, key: str) -> Any:
        if key not in self._store:
            self._misses += 1
            return None
        self._hits += 1
        value = self._store.pop(key)
        self._store[key] = value
        return value

    def get_stats(self) -> dict[str, Any]:
        total = self._hits + self._misses
        return {
            "hits": self._hits,
            "misses": self._misses,
            "hit_rate": (self._hits / total) if total else 0.0,
            "size": len(self._store),
            "max_size": self._max_size,
        }


__all__ = [
    "QueryCache",
    "InMemoryStatisticsManager",
    "QueryPlanner",
    "SimpleCostModel",
    "OptimizationLevel",
]
