from __future__ import annotations

from typing import Any

from .cache import get_or_fetch
from .config import CACHE_TTL_DAYS
from .http_client import get_json

import os

BASE_URL = os.environ.get("DATAGOUV_API_BASE_URL", "https://www.data.gouv.fr/api/1")
TTL_SECONDS = CACHE_TTL_DAYS * 24 * 3600


def fetch_dataset(slug_or_id: str) -> dict[str, Any]:
    return get_json(f"{BASE_URL}/datasets/{slug_or_id}/")


def get_dataset(slug_or_id: str, *, force: bool = False) -> dict[str, Any]:
    item = get_or_fetch(
        f"datagouv_dataset_{slug_or_id}",
        TTL_SECONDS,
        lambda: fetch_dataset(slug_or_id),
        force=force,
        source=f"{BASE_URL}/datasets/{slug_or_id}/",
    )
    return item["payload"]


def search_datasets(query: str, *, force: bool = False) -> dict[str, Any]:
    key = "datagouv_search_" + query.lower().replace(" ", "_")[:80]
    item = get_or_fetch(
        key,
        TTL_SECONDS,
        lambda: get_json(f"{BASE_URL}/datasets/", params={"q": query}),
        force=force,
        source=f"{BASE_URL}/datasets/?q={query}",
    )
    return item["payload"]


def resources_matching(dataset: dict[str, Any], *, terms: list[str] | None = None, formats: list[str] | None = None) -> list[dict[str, Any]]:
    terms = [t.lower() for t in (terms or [])]
    formats = [f.lower() for f in (formats or [])]
    resources = dataset.get("resources", []) or []
    out = []
    for resource in resources:
        title = " ".join(str(resource.get(k) or "") for k in ("title", "description", "url")).lower()
        fmt = str(resource.get("format") or "").lower()
        if terms and not all(term in title for term in terms):
            continue
        if formats and fmt not in formats:
            continue
        out.append(resource)
    return out
