"""Configuration and API key management."""

from __future__ import annotations

import os
from dataclasses import dataclass, field
from typing import Any


# Cache TTL (in seconds)
CACHE_TTL_ROUTE = 600  # 경로 검색: 10분
CACHE_TTL_STATION = 86400  # 정류장/역 정보: 1일
CACHE_TTL_CONGESTION = 3600  # 혼잡도: 1시간


@dataclass
class Config:
    """API key and configuration holder, reads from environment variables."""

    odsay_api_key: str = ""
    seoul_bus_api_key: str = ""
    seoul_subway_api_key: str = ""

    def __post_init__(self) -> None:
        self.odsay_api_key = self.odsay_api_key or os.environ.get("ODSAY_API_KEY", "")
        self.seoul_bus_api_key = self.seoul_bus_api_key or os.environ.get("SEOUL_BUS_API_KEY", "")
        self.seoul_subway_api_key = self.seoul_subway_api_key or os.environ.get("SEOUL_SUBWAY_API_KEY", "")


@dataclass
class SimpleCache:
    """Minimal TTL cache backed by a dict.  No external dependencies."""

    _store: dict[str, tuple[float, Any]] = field(default_factory=dict)

    def get(self, key: str, now: float) -> Any | None:
        entry = self._store.get(key)
        if entry is None:
            return None
        expires, value = entry
        if now >= expires:
            del self._store[key]
            return None
        return value

    def set(self, key: str, value: Any, ttl: float, now: float) -> None:
        self._store[key] = (now + ttl, value)

    def clear(self) -> None:
        self._store.clear()


# Singleton instances
config = Config()
cache = SimpleCache()
