"""Temp-file registry with TTL-based GC."""
from __future__ import annotations

import contextlib
import os
import tempfile
import time
from pathlib import Path

TEMP_DIR = Path(tempfile.mkdtemp(prefix="vcf_"))
_REGISTRY_TTL = float(os.environ.get("TEMP_FILE_TTL_SECONDS", "7200"))  # 2 h default
_registry: dict[str, tuple[Path, float]] = {}


def _registry_put(fid: str, path: Path) -> None:
    _registry[fid] = (path, time.monotonic())
    _registry_gc()


def _registry_get(fid: str) -> Path | None:
    entry = _registry.get(fid)
    return entry[0] if entry else None


def _registry_gc() -> None:
    cutoff = time.monotonic() - _REGISTRY_TTL
    stale = [k for k, (_, ts) in _registry.items() if ts < cutoff]
    for k in stale:
        path, _ = _registry.pop(k)
        with contextlib.suppress(Exception):
            path.unlink(missing_ok=True)
