"""
Query result cache — in-memory with TTL.
For production, swap with Redis using the same interface.
"""

import time
import os


class QueryCache:
    def __init__(self):
        self._store = {}
        self.ttl_seconds = int(os.getenv("CACHE_TTL_SECONDS", 3600))  # default 1 hour
        self.enabled = os.getenv("CACHE_ENABLED", "true").lower() == "true"

    def get(self, key: str):
        if not self.enabled:
            return None
        entry = self._store.get(key)
        if not entry:
            return None
        if time.time() - entry["timestamp"] > self.ttl_seconds:
            del self._store[key]
            return None
        return entry["value"]

    def set(self, key: str, value):
        if not self.enabled:
            return
        self._store[key] = {
            "value": value,
            "timestamp": time.time(),
        }

    def clear(self):
        self._store = {}

    def stats(self) -> dict:
        return {
            "entries": len(self._store),
            "ttl_seconds": self.ttl_seconds,
            "enabled": self.enabled,
        }
