"""In-memory TTL caching — projects, findings, score history.

Simple cachetools.TTLCache wrappers. No Redis, no external service.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from cachetools import TTLCache

if TYPE_CHECKING:
    from backend.dashboard.context import DashboardProjectCard

_projects_cache: TTLCache[str, list[DashboardProjectCard]] = TTLCache(
    maxsize=256,
    ttl=30,
)

_findings_cache: TTLCache[str, list[dict[str, Any]]] = TTLCache(
    maxsize=128,
    ttl=300,
)

_score_history_cache: TTLCache[str, list[dict[str, Any]]] = TTLCache(
    maxsize=256,
    ttl=300,
)


def get_cached_projects(customer_id: str) -> list[DashboardProjectCard] | None:
    """Return cached project cards or None on miss."""
    return _projects_cache.get(customer_id)


def set_cached_projects(
    customer_id: str,
    projects: list[DashboardProjectCard],
) -> None:
    """Cache project cards for 30 seconds."""
    _projects_cache[customer_id] = projects


def get_cached_findings(
    customer_id: str,
    project_id: str,
    scan_id: str,
) -> list[dict[str, Any]] | None:
    """Return cached findings or None on miss."""
    key = f"{customer_id}:{project_id}:{scan_id}"
    return _findings_cache.get(key)


def set_cached_findings(
    customer_id: str,
    project_id: str,
    scan_id: str,
    findings: list[dict[str, Any]],
) -> None:
    """Cache findings for 5 minutes."""
    key = f"{customer_id}:{project_id}:{scan_id}"
    _findings_cache[key] = findings


def get_cached_score_history(
    customer_id: str,
    project_id: str,
) -> list[dict[str, Any]] | None:
    """Return cached score history or None on miss."""
    key = f"{customer_id}:{project_id}"
    return _score_history_cache.get(key)


def set_cached_score_history(
    customer_id: str,
    project_id: str,
    history: list[dict[str, Any]],
) -> None:
    """Cache score history for 5 minutes."""
    key = f"{customer_id}:{project_id}"
    _score_history_cache[key] = history
