"""Download the published OSM-derived tiles. Python 3, standard library only.

Usage: python map_tiles.py <credits.html URL or local path> <output directory>
Data: (c) OpenStreetMap contributors, ODbL 1.0
https://www.openstreetmap.org/copyright
https://opendatacommons.org/licenses/odbl/1-0/
"""
import argparse
import base64
import gzip
import json
from pathlib import Path
import re
from urllib.parse import urljoin, urlsplit
from urllib.request import urlopen


def unpack(source, dest):
    if urlsplit(source).scheme.lower() not in {"https", "http", "file"}:
        source = Path(source).resolve().as_uri()
    assets = urljoin(source, "assets/local-map/")

    def read(filename):
        with urlopen(urljoin(assets, filename), timeout=30) as stream:
            return stream.read().decode("ascii")

    index = re.fullmatch(r"window\.LOCAL_MAP_TILES=(.+);\s*", read("index.js"))
    if index is None:
        raise ValueError("Unexpected map index")
    dest.mkdir(parents=True, exist_ok=True)
    (dest / "ATTRIBUTION.txt").write_text(
        "Regional basemap derived from Protomaps. © OpenStreetMap contributors. ODbL 1.0\n"
        "https://www.openstreetmap.org/copyright\nhttps://opendatacommons.org/licenses/odbl/1-0/\n"
        "Includes Natural Earth public domain data. https://docs.protomaps.com/basemaps/downloads\n"
        + source + "\n", encoding="utf-8")
    for z, columns in json.loads(index[1]).items():
        for x, rows in columns.items():
            folder = dest / str(int(z)) / str(int(x))
            folder.mkdir(parents=True, exist_ok=True)
            for y in rows:
                basename = f"{int(z)}-{int(x)}-{int(y)}.js"
                value = re.fullmatch(r'document\.currentScript\.mapTile="([A-Za-z0-9+/=]+)";\s*', read(basename))
                if value is None:
                    raise ValueError("Unexpected tile: " + basename)
                data = gzip.decompress(base64.b64decode(value[1], validate=True))
                (folder / f"{int(y)}.mvt").write_bytes(data)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source")
    parser.add_argument("dest", type=Path)
    options = parser.parse_args()
    unpack(options.source, options.dest)
