from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Any

BASE_DIR = Path(__file__).resolve().parents[1]
DATA_DIR = BASE_DIR / "data"
CACHE_DIR = Path(os.environ.get("FONCIER_CACHE_DIR", str(DATA_DIR / "cache")))
SCOPE_PATH = Path(os.environ.get("FONCIER_AGENCY_SCOPE", str(DATA_DIR / "agency_scope.json")))
HTTP_TIMEOUT = float(os.environ.get("FONCIER_HTTP_TIMEOUT", "30"))
CACHE_TTL_DAYS = int(os.environ.get("FONCIER_CACHE_TTL_DAYS", "30"))
USER_AGENT = os.environ.get(
    "FONCIER_USER_AGENT",
    "AULA-Foncier-Narratif/0.1 (+https://www.aulartois.fr)",
)


def ensure_dirs() -> None:
    CACHE_DIR.mkdir(parents=True, exist_ok=True)


def load_json(path: Path, default: Any | None = None) -> Any:
    if not path.exists():
        return default
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)


def save_json(path: Path, data: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)


def load_scope() -> dict[str, Any]:
    scope = load_json(SCOPE_PATH, default={}) or {}
    env_codes = os.environ.get("FONCIER_AGENCY_EPCI_CODES")
    if env_codes:
        epcis = []
        names = {str(item.get("code")): item for item in scope.get("epcis", []) if item.get("code")}
        for code in [c.strip() for c in env_codes.split(",") if c.strip()]:
            epcis.append(names.get(code, {"code": code, "name": code, "short_name": code}))
        scope["epcis"] = epcis
    return scope


def agency_epci_codes() -> list[str]:
    return [str(item["code"]) for item in load_scope().get("epcis", []) if item.get("code")]
