from __future__ import annotations

import os
from pathlib import Path
from typing import Any

import httpx


class DataGouvClient:
    def __init__(self, base_url: str | None = None, timeout: float = 30.0):
        self.base_url = (base_url or os.getenv("DATAGOUV_API_BASE_URL") or "https://www.data.gouv.fr/api/1").rstrip("/")
        self.timeout = timeout

    def dataset(self, slug: str) -> dict[str, Any]:
        url = f"{self.base_url}/datasets/{slug}/"
        with httpx.Client(timeout=self.timeout, follow_redirects=True) as client:
            response = client.get(url)
            response.raise_for_status()
            return response.json()

    @staticmethod
    def slim_dataset(payload: dict[str, Any]) -> dict[str, Any]:
        resources = []
        for r in payload.get("resources", []) or []:
            resources.append(
                {
                    "id": r.get("id"),
                    "title": r.get("title"),
                    "format": r.get("format"),
                    "url": r.get("url"),
                    "latest": r.get("latest"),
                    "filesize": r.get("filesize"),
                    "created_at": r.get("created_at"),
                    "last_modified": r.get("last_modified"),
                }
            )
        return {
            "id": payload.get("id"),
            "slug": payload.get("slug"),
            "title": payload.get("title"),
            "description": payload.get("description"),
            "license": (payload.get("license") or {}).get("title") if isinstance(payload.get("license"), dict) else payload.get("license"),
            "last_update": payload.get("last_update"),
            "resources": resources,
        }

    def download_resource(self, url: str, output_path: Path) -> Path:
        output_path.parent.mkdir(parents=True, exist_ok=True)
        with httpx.stream("GET", url, timeout=self.timeout, follow_redirects=True) as response:
            response.raise_for_status()
            with output_path.open("wb") as f:
                for chunk in response.iter_bytes():
                    if chunk:
                        f.write(chunk)
        return output_path
