
from __future__ import annotations

import csv
from pathlib import Path
from typing import Any

BASE_DIR = Path(__file__).resolve().parents[2]
DEFAULT_CACHE = BASE_DIR / "data" / "cache" / "conso_enaf_communes.csv"


def status() -> dict[str, Any]:
    return {
        "configured": DEFAULT_CACHE.exists(),
        "mode": "data_gouv_download_or_cached_csv",
        "cache_file": str(DEFAULT_CACHE.relative_to(BASE_DIR)),
        "planned_indicators": [
            "consommation ENAF annuelle",
            "consommation totale 2009-2024",
            "rythme moyen annuel",
            "trajectoire ZAN",
        ],
    }


def load_cached_rows(code_insee: str | None = None) -> list[dict[str, Any]]:
    if not DEFAULT_CACHE.exists():
        return []
    with DEFAULT_CACHE.open("r", encoding="utf-8-sig", newline="") as f:
        rows = list(csv.DictReader(f))
    if code_insee:
        possible = ("code_insee", "CODGEO", "code_commune", "codgeo")
        return [r for r in rows if any(str(r.get(k) or "") == str(code_insee) for k in possible)]
    return rows
