"""Disk-backed TTL cache for API responses (interactive TUI only)."""

from __future__ import annotations

import hashlib
import json
import time
from pathlib import Path

from xc_dl.api.models import APIResponse
from xc_dl.api.query import normalise_query
from xc_dl.paths import cache_dir


class SearchCache:
    """Disk-backed TTL cache for API responses."""

    def __init__(self, ttl_seconds: int = 300):
        self.cache_path = cache_dir() / "search"
        self.ttl = ttl_seconds

    def _key(self, query: str, page: int) -> str:
        raw = f"{normalise_query(query)}::{page}"
        return hashlib.sha256(raw.encode()).hexdigest()

    def get(self, query: str, page: int) -> APIResponse | None:
        try:
            path = self.cache_path / f"{self._key(query, page)}.json"
            if not path.exists():
                return None
            stat = path.stat()
            if time.time() - stat.st_mtime > self.ttl:
                return None
            data = json.loads(path.read_text())
            return APIResponse.model_validate(data)
        except Exception:
            return None

    def put(self, query: str, page: int, response: APIResponse) -> None:
        try:
            self.cache_path.mkdir(parents=True, exist_ok=True)
            path = self.cache_path / f"{self._key(query, page)}.json"
            path.write_text(response.model_dump_json(indent=2))
        except Exception:
            pass
