
from __future__ import annotations

import httpx
from typing import Any

BASE_URL = "https://geo.api.gouv.fr"
TIMEOUT = httpx.Timeout(20.0, connect=10.0)


async def _get_json(path: str, params: dict[str, str] | None = None) -> Any:
    async with httpx.AsyncClient(timeout=TIMEOUT) as client:
        response = await client.get(f"{BASE_URL}{path}", params=params)
        response.raise_for_status()
        return response.json()


async def fetch_epci(code_epci: str) -> dict[str, Any]:
    return await _get_json(f"/epcis/{code_epci}", {"fields": "nom,code"})


async def fetch_communes_for_epci(code_epci: str) -> list[dict[str, Any]]:
    params = {"fields": "nom,code,codesPostaux,centre,surface,population"}
    communes = await _get_json(f"/epcis/{code_epci}/communes", params)
    for commune in communes:
        commune["code_epci"] = code_epci
    return communes


async def fetch_agency_communes(epci_codes: list[str]) -> dict[str, Any]:
    epcis: list[dict[str, Any]] = []
    communes_by_code: dict[str, dict[str, Any]] = {}
    for code in epci_codes:
        try:
            epci = await fetch_epci(code)
        except Exception:
            epci = {"code": code, "nom": None, "warning": "EPCI non recupere via API Geo"}
        epcis.append(epci)
        for commune in await fetch_communes_for_epci(code):
            current = communes_by_code.get(commune["code"])
            if not current:
                communes_by_code[commune["code"]] = commune
    return {
        "source": "api_geo",
        "epcis": epcis,
        "communes": sorted(communes_by_code.values(), key=lambda item: item.get("nom") or item.get("code")),
    }
