"""Cache memoire simple avec TTL — pas de dependance externe"""
import time
import threading

_store = {}
_lock = threading.Lock()
DEFAULT_TTL = 600  # 10 minutes


def get(key):
    with _lock:
        entry = _store.get(key)
        if entry is None:
            return None
        if time.time() > entry["expires"]:
            del _store[key]
            return None
        return entry["value"]


def set(key, value, ttl=DEFAULT_TTL):
    with _lock:
        _store[key] = {"value": value, "expires": time.time() + ttl}


def delete(key):
    with _lock:
        _store.pop(key, None)


def clear_prefix(prefix):
    with _lock:
        keys = [k for k in _store if k.startswith(prefix)]
        for k in keys:
            del _store[k]


def clear_all():
    with _lock:
        _store.clear()


def stats():
    with _lock:
        now = time.time()
        total = len(_store)
        active = sum(1 for v in _store.values() if now <= v["expires"])
        return {"total": total, "active": active}
