# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/05_datasets_geofabrik.ipynb (unless otherwise specified).

__all__ = ["list_geofabrik_regions", "download_geofabrik_region"]


# Internal Cell
import os
import shutil
from functools import lru_cache
from pathlib import Path
from urllib.parse import urlparse

# exporti
import requests

# Internal Cell
@lru_cache(maxsize=None)
def load_geofabrik_data():
    return requests.get("https://download.geofabrik.de/index-v1-nogeom.json").json()


# Cell
def list_geofabrik_regions() -> dict:
    """Get list of regions from geofabrik index"""
    geofrabik_data = load_geofabrik_data()
    return {
        k["properties"]["id"]: k["properties"]["urls"].get("shp")
        for k in geofrabik_data["features"]
        if k["properties"]["urls"].get("shp")
    }


# Cell
def download_geofabrik_region(
    region: str, directory: str = "data/", overwrite=False
) -> Path:
    """Download geofabrik region to path"""
    if not os.path.isdir(directory):
        os.makedirs(directory)
    geofabrik_info = list_geofabrik_regions()
    if region not in geofabrik_info:
        raise ValueError(
            f"{region} not found in geofabrik. Run list_geofabrik_regions() to learn more about available areas"
        )
    url = geofabrik_info[region]
    parsed_url = urlparse(url)
    filename = Path(os.path.basename(parsed_url.path))
    filepath = directory / filename
    if not filepath.exists() or overwrite:
        response = requests.get(url, stream=True)
        with open(filepath, "wb") as out_file:
            shutil.copyfileobj(response.raw, out_file)
    return filepath
