"""A heightmap of an island, with the sea around it, for the relief map generator.

    pip install rasterio numpy shapely
    python island.py OUT.png --at LON LAT --size WIDTH_KM [HEIGHT_KM] [--sea 1] [--width 900]
    python island.py OUT.png --at LON LAT --size WIDTH_KM [HEIGHT_KM] --seabed [--coast COAST.svg]

    python island.py tenerife.png --at -16.56 28.27 --size 88 72                  # Tenerife, the map in the post

- --at is the centre of the map in degrees, longitude first, east positive; --size its width and height on the
  ground in km (one number for a square). The map is reprojected to UTM, so the pixels are square, north up.
- Land comes from the free Copernicus 30 m model on AWS (Copernicus DEM GLO-30), read over HTTPS: only the tiles
  the map touches, and only the part of each it needs. The model has no tiles for open sea; those are sea here.
- The sea is black. Land runs from --sea per cent grey at the coast (default 1) to white at the highest point,
  so in the generator a *Sea level* of the same per cent floods exactly the sea: with shape `outline` the map is
  cut to the coastline, with `rectangle` or `circle` the coast is engraved on the base.
- --seabed: the sea floor too, from GEBCO's global 450 m grid (land and sea in one, public domain), read over the
  web. Black is then the deepest water; leave *Sea level* at 0, or the generator floods the sea floor.
- --coast: also write the coastline (0 m) as an SVG for the generator's *Markings*, one unit per pixel of the
  heightmap, so it lines up: engraved as a line on whichever layer it crosses.
- The picture is averaged down to --width pixels on its long side (the generator keeps at most 300 cells, so 300,
  600 or 900 are good choices). The script prints the heights black and white stand for.

Copernicus heightmaps carry a notice when you share them (the PNG, or a picture of it): "produced using Copernicus
WorldDEM-30 © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the
European Union and ESA; all rights reserved", and "The organisations in charge of the Copernicus programme by law
or by delegation do not incur any liability for any use of the Copernicus WorldDEM-30". GEBCO asks for credit:
"GEBCO Compilation Group (2024) GEBCO 2024 Grid", and its data is not for navigation.
"""

from __future__ import annotations

import argparse
import math
import struct
import zlib

import numpy as np
import rasterio
from rasterio.crs import CRS
from rasterio.errors import RasterioIOError
from rasterio.features import shapes
from rasterio.transform import Affine
from rasterio.warp import Resampling, reproject, transform as warp_points
from rasterio.windows import Window, from_bounds
from shapely.geometry import Polygon, shape

TILE = ("https://copernicus-dem-30m.s3.amazonaws.com/Copernicus_DSM_COG_10_{n}_00_{e}_00_DEM/"
        "Copernicus_DSM_COG_10_{n}_00_{e}_00_DEM.tif")
GEBCO = ("https://s3.us-west-2.amazonaws.com/us-west-2.opendata.source.coop/alexgleith/gebco-2024/"
         "GEBCO_2024.tif")       # GEBCO_2024 as one cloud-optimised GeoTIFF (Source Cooperative)
GDAL = {"GDAL_DISABLE_READDIR_ON_OPEN": "EMPTY_DIR", "GDAL_HTTP_MAX_RETRY": 5, "GDAL_HTTP_RETRY_DELAY": 2}


def utm(lon: float, lat: float) -> CRS:
    """The UTM zone a point lies in: a flat map in metres."""
    return CRS.from_epsg((32600 if lat >= 0 else 32700) + int((lon + 180) // 6) + 1)


def frame(lon: float, lat: float, size_km: tuple[float, float], width: int) -> tuple[CRS, Affine, int, int, float]:
    """The map's rectangle centred on (lon, lat): its CRS, pixels-to-metres transform, size in pixels, pixel size."""
    crs = utm(lon, lat)
    (cx,), (cy,) = warp_points("EPSG:4326", crs, [lon], [lat])
    w_m, h_m = size_km[0] * 1000, size_km[1] * 1000
    pixel = max(w_m, h_m) / width
    cols, rows = round(w_m / pixel), round(h_m / pixel)
    return crs, Affine(pixel, 0, cx - cols * pixel / 2, 0, -pixel, cy + rows * pixel / 2), cols, rows, pixel


def lonlat_bounds(crs: CRS, dst: Affine, cols: int, rows: int) -> tuple[float, float, float, float]:
    """West, south, east, north of the map in degrees, from points along its edges, with a small margin."""
    t = np.linspace(0, 1, 21)
    xs = np.r_[t * cols, np.full(21, cols), t * cols, np.zeros(21)]
    ys = np.r_[np.zeros(21), t * rows, np.full(21, rows), t * rows]
    lon, lat = warp_points(crs, "EPSG:4326", *(dst * (xs, ys)))
    return min(lon) - 0.01, min(lat) - 0.01, max(lon) + 0.01, max(lat) + 0.01


def add(out: np.ndarray, source: str, bounds: tuple, crs: CRS, dst: Affine, pixel: float) -> bool:
    """Reproject the part of `source` inside `bounds` (degrees) into `out`, where it has data; False if no file."""
    try:
        src = rasterio.open(source)
    except RasterioIOError:
        return False
    with src:
        win = from_bounds(*bounds, src.transform).round_offsets().round_lengths()
        win = win.intersection(Window(0, 0, src.width, src.height))
        z = src.read(1, window=win, masked=True).astype("float32").filled(np.nan)
        src_pixel = abs(src.transform.e) * math.pi / 180 * 6_371_000             # metres, north-south
        part = np.full(out.shape, np.nan, "float32")
        reproject(z, part, src_transform=src.window_transform(win), src_crs=src.crs, src_nodata=np.nan,
                  dst_transform=dst, dst_crs=crs, dst_nodata=np.nan,
                  resampling=Resampling.average if src_pixel < pixel else Resampling.bilinear)
    np.copyto(out, part, where=~np.isnan(part))
    return True


def heightmap(lon: float, lat: float, size_km: tuple[float, float], width: int = 900,
              seabed: bool = False) -> tuple[np.ndarray, Affine, float]:
    """Heights in metres on a square-pixel grid around (lon, lat), sea at 0 m or below; with the map's transform."""
    lon = (lon + 180) % 360 - 180
    crs, dst, cols, rows, pixel = frame(lon, lat, size_km, width)
    w, s, e, n = lonlat_bounds(crs, dst, cols, rows)
    out = np.full((rows, cols), np.nan, "float32")
    with rasterio.Env(**GDAL):
        if seabed:
            add(out, GEBCO, (w, s, e, n), crs, dst, pixel)
        else:
            found = [add(out, TILE.format(n=f"{'N' if y >= 0 else 'S'}{abs(y):02d}",
                                          e=f"{'E' if x >= 0 else 'W'}{abs(x):03d}"), (w, s, e, n), crs, dst, pixel)
                     for y in range(math.floor(s), math.floor(n) + 1) for x in range(math.floor(w), math.floor(e) + 1)]
            if not any(found):
                raise SystemExit("no land here in the Copernicus model: check --at (longitude first)")
            out[np.isnan(out)] = 0                                     # no tile: open sea
    if np.isnan(out).any():
        raise SystemExit(f"{np.isnan(out).mean():.1%} of the map has no data: move --at or make --size smaller")
    return out, dst, pixel


def grey(z: np.ndarray, sea: float) -> tuple[np.ndarray, float, float]:
    """0..1 per pixel: sea 0, land from `sea` (a share) at 0 m to 1 at the top. With sea = None, plain lowest to
    highest. Returns the picture and the heights black and white stand for."""
    hi = float(z.max())
    if sea is None:
        lo = float(z.min())
        return (z - lo) / (hi - lo), lo, hi
    land = z > 0
    return np.where(land, sea + (1 - sea) * np.maximum(z, 0) / hi, 0.0), 0.0, hi


def png16(g: np.ndarray, path: str) -> None:
    """Save a 0..1 picture as a 16-bit greyscale PNG."""
    px = np.round(np.clip(g, 0, 1) * 65535).astype(">u2")             # PNG wants big-endian samples
    raw = b"".join(b"\0" + row.tobytes() for row in px)                 # filter type 0 on every row

    def chunk(kind: bytes, body: bytes) -> bytes:
        return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))

    head = struct.pack(">IIBBBBB", g.shape[1], g.shape[0], 16, 0, 0, 0, 0)   # 16 bits, grey
    with open(path, "wb") as f:
        f.write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", head) + chunk(b"IDAT", zlib.compress(raw, 9))
                + chunk(b"IEND", b""))


def coast_svg(z: np.ndarray, path: str, min_px: float = 4) -> int:
    """The 0 m coastline as stroked SVG paths, one unit per heightmap pixel; islets under `min_px` pixels are left
    out. Returns the number of coastlines (islands and lakes)."""
    land = z > 0
    rings = []
    for geom, _ in shapes(land.astype("uint8"), mask=land):
        poly = shape(geom).simplify(0.5)
        for ring in (poly.exterior, *poly.interiors):
            if Polygon(ring).area >= min_px:
                rings.append("M" + " L".join(f"{x:.1f} {y:.1f}" for x, y in ring.coords) + " Z")
    h, w = z.shape
    with open(path, "w") as f:
        f.write(f'<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}">'
                f'<path d="{" ".join(rings)}" fill="none" stroke="black" stroke-width="2"/></svg>\n')
    return len(rings)


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("out")
    ap.add_argument("--at", type=float, nargs=2, metavar=("LON", "LAT"), required=True, help="centre, degrees")
    ap.add_argument("--size", type=float, nargs="+", metavar="KM", required=True, help="width [height] in km")
    ap.add_argument("--width", type=int, default=900, help="pixels on the long side (default 900)")
    ap.add_argument("--sea", type=float, default=1, help="land starts at this %% grey; set Sea level to it")
    ap.add_argument("--seabed", action="store_true", help="the sea floor too, from GEBCO (450 m)")
    ap.add_argument("--coast", metavar="SVG", help="also write the coastline as markings")
    a = ap.parse_args()
    z, _, pixel = heightmap(*a.at, (a.size[0], a.size[-1]), a.width, a.seabed)
    g, lo, hi = grey(z, None if a.seabed else a.sea / 100)
    png16(g, a.out)
    print(f"{z.shape[1]} x {z.shape[0]} px of {pixel:.0f} m ({z.shape[1] * pixel / 1000:.0f} x "
          f"{z.shape[0] * pixel / 1000:.0f} km), {(z <= 0).mean():.0%} sea; black = {lo:.0f} m, white = {hi:.0f} m"
          + ("" if a.seabed else f"; land from {a.sea:g} % grey: set Sea level to {a.sea:g} %"))
    if a.coast:
        print(f"{a.coast}: {coast_svg(z, a.coast)} coastlines")
