from __future__ import annotations

from pathlib import Path
import os
from typing import Any

from .config import CACHE_DIR
from .csv_filter import download_filter_csv
from .datagouv import get_dataset, resources_matching
from .geo_api import agency_scope

DATASET_SLUG = os.environ.get("SITADEL_DATASET_SLUG", "liste-des-permis-de-construire-et-autres-autorisations-durbanisme")
CODE_COLUMNS_COMMUNE = ["code_commune", "codgeo", "code_geo", "code_insee", "coddepcom", "insee", "commune"]


def metadata(*, force: bool = False) -> dict[str, Any]:
    dataset = get_dataset(DATASET_SLUG, force=force)
    resources = {
        "logements": resources_matching(dataset, terms=["logements"], formats=["csv", "zip"]),
        "locaux": resources_matching(dataset, terms=["locaux"], formats=["csv", "zip"]),
        "amenager": resources_matching(dataset, terms=["aménager"], formats=["csv", "zip"])
        or resources_matching(dataset, terms=["amenager"], formats=["csv", "zip"]),
        "demolir": resources_matching(dataset, terms=["démolir"], formats=["csv", "zip"])
        or resources_matching(dataset, terms=["demolir"], formats=["csv", "zip"]),
    }
    return {
        "dataset": {
            "id": dataset.get("id"),
            "title": dataset.get("title"),
            "slug": dataset.get("slug"),
            "page": dataset.get("page"),
            "last_update": dataset.get("last_update"),
            "frequency": dataset.get("frequency"),
            "license": (dataset.get("license") or {}).get("title") if isinstance(dataset.get("license"), dict) else dataset.get("license"),
        },
        "resources": resources,
    }


def _best_resource(kind: str, *, force: bool = False) -> dict[str, Any] | None:
    candidates = metadata(force=force)["resources"].get(kind, [])
    csv_candidates = [r for r in candidates if str(r.get("format") or "").lower() == "csv"]
    return (csv_candidates or candidates or [None])[0]


def refresh_filtered_cache(kind: str = "logements", *, force: bool = False) -> dict[str, Any]:
    resource = _best_resource(kind, force=force)
    if not resource:
        return {"ok": False, "error": f"Aucune ressource Sitadel {kind} trouvée", "kind": kind}
    url = resource.get("url") or resource.get("latest")
    if not url:
        return {"ok": False, "error": "Ressource sans URL", "resource": resource}
    scope = agency_scope(live=True, force=force)
    codes = {str(c.get("code")) for c in scope.get("communes", []) if c.get("code")}
    output = CACHE_DIR / f"sitadel_{kind}_aula.csv"
    result = download_filter_csv(url, output, codes, CODE_COLUMNS_COMMUNE)
    return {"ok": True, "kind": kind, "resource": {"title": resource.get("title"), "url": url}, "filter": result}
