"""Build the compact world-outline data used by the ground-track figures.

Source: Natural Earth 1:110m land polygons (public domain, naturalearthdata.com).
Coordinates are rounded to 0.1 deg (about 11 km, finer than the source's own scale)
and stored as integers (tenths of a degree):

    codes/data/land110.json   read by the matplotlib scripts (fig-gt-*.py)
    js/land110.js             read by the interactive ground-track simulator

Run from the deck directory:   python codes/make-land-data.py
"""
import json
import os
import urllib.request

URL = "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_110m_land.geojson"
SRC = "codes/_cache/ne_110m_land.geojson"

os.makedirs("codes/_cache", exist_ok=True)
os.makedirs("codes/data", exist_ok=True)
os.makedirs("js", exist_ok=True)
if not os.path.exists(SRC):
    urllib.request.urlretrieve(URL, SRC)

rings = []
for ft in json.load(open(SRC))["features"]:
    g = ft["geometry"]
    polys = g["coordinates"] if g["type"] == "MultiPolygon" else [g["coordinates"]]
    for poly in polys:
        ring = poly[0]                       # outer boundary; the 110m data has no lakes worth keeping
        flat, last = [], None
        for lon, lat in ring:
            p = (round(lon*10), round(lat*10))
            if p != last:
                flat += p
                last = p
        rings.append(flat)

json.dump(rings, open("codes/data/land110.json", "w"), separators=(",", ":"))
with open("js/land110.js", "w") as f:
    f.write("// Natural Earth 1:110m land (public domain). Rings as flat [lon, lat, ...] in tenths of a degree.\n")
    f.write("window.GT_LAND=" + json.dumps(rings, separators=(",", ":")) + ";\n")
print(len(rings), "rings,", sum(len(r)//2 for r in rings), "points;",
      os.path.getsize("js/land110.js")//1024, "KiB")
