"""Index of French territories (communes, EPCI, départements, régions) and name resolution. The full commune list, with each commune's EPCI, département and région, is read once from a data cube exposing every geographic level (~35 000 rows, a few seconds), in the background after the metadata cache is loaded. It serves: - name → code resolution, exact match first (find_territory, query_indicator_data(territory=…)); - parent territories, used to suggest a coarser level when a level has no data. When the index cannot be loaded, callers fall back to a `contains` lookup in the API. """ import asyncio import logging import re from collections import Counter from dataclasses import dataclass, field from typing import Any from .api_client import CubeJsClient, CubeJsClientError, get_client from .cache import fold_text from .cube_resolver import get_resolver from .models import GEO_DIMENSION_PATTERNS, REGION_ALIASES, REGION_CODES logger = logging.getLogger("mcp_tools") LEVEL_ORDER = ["commune", "epci", "departement", "region"] # finest first _WORD_RE = re.compile(r"[a-z0-9]+") # Words ignored when comparing names (« Métropole de Lyon » ~ « Metropole Lyon ») _NAME_STOP_WORDS = {"de", "du", "des", "la", "le", "les", "l", "d", "et", "en", "a", "aux", "au"} def normalize_name(text: str | None) -> str: """Folded name with punctuation as spaces (« Saint-Brieuc » → « saint brieuc »).""" return " ".join(_WORD_RE.findall(fold_text(text))) def _name_words(text: str | None) -> list[str]: return [w for w in normalize_name(text).split() if w not in _NAME_STOP_WORDS] @dataclass class Territory: level: str geocode: str libelle: str # parent codes by level (commune → epci, departement, region; epci → departement, region…) parents: dict[str, str] = field(default_factory=dict) norm: str = "" words: tuple[str, ...] = () def __post_init__(self) -> None: self.norm = normalize_name(self.libelle) self.words = tuple(_name_words(self.libelle)) @dataclass class Match: territory: Territory rank: int # 3 exact name or code, 2 same significant words, 1 all query words in the name @property def exact(self) -> bool: return self.rank == 3 def _match_rank(query_norm: str, query_words: list[str], t: Territory) -> int: if query_norm == t.norm or query_norm == t.geocode.lower(): return 3 if not query_words: return 0 if sorted(query_words) == sorted(t.words): return 2 if all(any(w == q or (len(q) >= 4 and w.startswith(q)) for w in t.words) for q in query_words): return 1 return 0 def sort_matches(matches: list[Match]) -> list[Match]: return sorted(matches, key=lambda m: (-m.rank, len(m.territory.libelle), LEVEL_ORDER.index(m.territory.level))) def search_regions(name: str) -> list[Match]: """Regions are resolved locally (no API call), abbreviations included (PACA, IDF…).""" query_norm = normalize_name(name) if not query_norm: return [] alias = REGION_ALIASES.get(query_norm.replace(" ", "")) if alias: return [Match(Territory("region", alias, REGION_CODES[alias]), 3)] query_words = _name_words(name) matches = [] for code, label in REGION_CODES.items(): t = Territory("region", code, label) rank = _match_rank(query_norm, query_words, t) if rank: matches.append(Match(t, rank)) return sort_matches(matches) def pick(matches: list[Match]) -> Territory | None: """The territory designated by a name: the only best-ranked match, if any.""" if not matches: return None best = [m for m in matches if m.rank == matches[0].rank] return best[0].territory if len(best) == 1 else None class TerritoryIndex: def __init__(self) -> None: self.by_level: dict[str, dict[str, Territory]] = {lv: {} for lv in LEVEL_ORDER} self.epci_communes: dict[str, list[str]] = {} self.loaded = False def load_rows(self, rows: list[dict[str, Any]], cube: str) -> None: """Build the index from commune rows carrying every level's code (and label).""" def col(level: str, kind: str) -> str: return f"{cube}.{GEO_DIMENSION_PATTERNS[level][kind]}" by_level: dict[str, dict[str, Territory]] = {lv: {} for lv in LEVEL_ORDER} epci_communes: dict[str, list[str]] = {} epci_dpts: dict[str, Counter] = {} dpt_region: dict[str, str] = {} for row in rows: com, epci = row.get(col("commune", "geocode")), row.get(col("epci", "geocode")) dpt, reg = row.get(col("departement", "geocode")), row.get(col("region", "geocode")) if com: parents = {lv: c for lv, c in (("epci", epci), ("departement", dpt), ("region", reg)) if c} by_level["commune"][com] = Territory("commune", com, row.get(col("commune", "libelle")) or com, parents) if epci: if epci not in by_level["epci"]: by_level["epci"][epci] = Territory("epci", epci, row.get(col("epci", "libelle")) or epci) if com: epci_communes.setdefault(epci, []).append(com) if dpt: epci_dpts.setdefault(epci, Counter())[dpt] += 1 if dpt and dpt not in by_level["departement"]: by_level["departement"][dpt] = Territory( "departement", dpt, row.get(col("departement", "libelle")) or dpt ) if dpt and reg: dpt_region[dpt] = reg for code, t in by_level["departement"].items(): if code in dpt_region: t.parents["region"] = dpt_region[code] for code, t in by_level["epci"].items(): if code in epci_dpts: main_dpt = epci_dpts[code].most_common(1)[0][0] t.parents["departement"] = main_dpt if main_dpt in dpt_region: t.parents["region"] = dpt_region[main_dpt] regions = set(dpt_region.values()) | set(REGION_CODES) for code in regions: by_level["region"][code] = Territory("region", code, REGION_CODES.get(code, code)) self.by_level = by_level self.epci_communes = epci_communes self.loaded = True def get(self, level: str, code: str) -> Territory | None: return self.by_level.get(level, {}).get(code) def search(self, name: str, levels: list[str]) -> list[Match]: """Territories matching a name at the given levels, best first (exact match first).""" query_norm = normalize_name(name) query_words = _name_words(name) if not query_norm: return [] matches: list[Match] = [] for level in levels: if level == "region": matches.extend(search_regions(name)) continue for t in self.by_level.get(level, {}).values(): rank = _match_rank(query_norm, query_words, t) if rank: matches.append(Match(t, rank)) return sort_matches(matches) def main_commune(self, epci_code: str) -> Territory | None: """Commune whose name appears in the EPCI name (Montpellier for « Montpellier Méditerranée Métropole »).""" epci = self.get("epci", epci_code) if epci is None: return None found = [ self.by_level["commune"][c] for c in self.epci_communes.get(epci_code, []) if c in self.by_level["commune"] and self.by_level["commune"][c].norm and f" {self.by_level['commune'][c].norm} " in f" {epci.norm} " ] return max(found, key=lambda t: len(t.norm), default=None) def coarser(self, territory: Territory) -> list[Territory]: """Parent territories, finest first (commune → EPCI, département, région).""" out = [] for level in LEVEL_ORDER[LEVEL_ORDER.index(territory.level) + 1:]: code = territory.parents.get(level) parent = self.get(level, code) if code else None if parent: out.append(parent) return out _index = TerritoryIndex() _load_task: asyncio.Task | None = None def get_territory_index() -> TerritoryIndex: return _index async def _load(client: CubeJsClient) -> None: resolver = get_resolver() cube = resolver.find_cube_with_maille("commune") if cube is None: raise CubeJsClientError("No data cube exposes the commune level.") dims = [ f"{cube}.{GEO_DIMENSION_PATTERNS[lv][kind]}" for lv in LEVEL_ORDER for kind in ("geocode", "libelle") if lv != "region" or kind == "geocode" ] available = set(resolver.get_cube_dimensions(cube)) dims = [d for d in dims if d in available] result = await client.load({"dimensions": dims, "limit": 50000}) index = TerritoryIndex() index.load_rows(result.get("data", []), cube) global _index _index = index logger.info( "[TERRITORIES] loaded from %s | %s", cube, {lv: len(index.by_level[lv]) for lv in LEVEL_ORDER}, ) def start_loading(client: CubeJsClient | None = None) -> None: """Load the index in the background (no-op if loaded or loading).""" global _load_task if _index.loaded or (_load_task is not None and not _load_task.done()): return _load_task = asyncio.get_running_loop().create_task(_load(client or get_client())) async def ensure_loaded(timeout: float = 30.0) -> TerritoryIndex | None: """Wait for the index; None if it could not be loaded (callers fall back to the API).""" global _load_task if _index.loaded: return _index if _load_task is None or (_load_task.done() and _load_task.exception() is not None): _load_task = None start_loading() try: await asyncio.wait_for(asyncio.shield(_load_task), timeout) # type: ignore[arg-type] except Exception as e: # noqa: BLE001 — any failure means "no index" logger.warning("[TERRITORIES] index unavailable: %s", e) return None return _index if _index.loaded else None