from __future__ import annotations

from functools import lru_cache
from pathlib import Path

from pydantic import BaseModel

CONFIG_PATH = Path(__file__).resolve().parent.parent.parent / "config_backend.json"
# chemin vers la conf JSON partagée entre les composants backend


class AppConfig(BaseModel):
    env: str
    version: str
    base_url: str
    log_level: str


class ScrapeConfig(BaseModel):
    interval_minutes: int
    headless: bool
    timeout_ms: int
    retries: int
    delay_range_ms: tuple[int, int]
    user_agent: str
    viewport: dict[str, int]
    locale: str
    timezone: str
    proxy: str | None


class TaxonomyConfig(BaseModel):
    categories: list[str]
    types_by_category: dict[str, list[str]]


class BackendConfig(BaseModel):
    app: AppConfig
    scrape: ScrapeConfig
    stores_enabled: list[str]
    taxonomy: TaxonomyConfig


@lru_cache(maxsize=1)
def load_config() -> BackendConfig:
    # on met en cache pour éviter de recharger le fichier à chaque requête
    return BackendConfig.model_validate_json(CONFIG_PATH.read_text(encoding="utf-8"))
