"""Cut a heightmap of a crater, a volcano or a canyon out of a global Moon or Mars elevation model, for the relief
map generator.

    pip install rasterio numpy
    python planet.py SOURCE OUT.png --at LON LAT --size WIDTH_KM [HEIGHT_KM] [--width 900]

SOURCE is a global elevation GeoTIFF from the USGS Astrogeology Science Center (a local file or its URL; only the
part around --at is read, so a URL works without downloading gigabytes), for example:

    Moon, LRO LOLA 118 m:  https://planetarymaps.usgs.gov/mosaic/Lunar_LRO_LOLA_Global_LDEM_118m_Mar2014.tif
    Mars, MOLA 463 m:      https://planetarymaps.usgs.gov/mosaic/Mars_MGS_MOLA_DEM_mosaic_global_463m.tif
    Mars, MOLA + HRSC 200 m:
        https://planetarymaps.usgs.gov/mosaic/Mars/HRSC_MOLA_Blend/Mars_HRSC_MOLA_BlendDEM_Global_200mp_v2.tif

- --at is the centre of the map in degrees, longitude first, east positive (-180 to 180, or 0 to 360).
- --size is the map's width and height on the ground in km (one number for a square).
- These grids are "simple cylindrical": one pixel per fraction of a degree. Away from the equator a degree of
  longitude is shorter than a degree of latitude (by the cosine of the latitude), so the pixels are not square on
  the ground and a crater cut straight out of the grid comes out oval. The script reprojects the area to a flat
  map centred on --at (azimuthal equidistant, on the Moon's or Mars's own sphere), so the pixels are square and
  north is up.
- 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). For a big area it reads one of the file's smaller copies (overviews) when it has
  them, which is much faster over the web.
- The PNG is 16-bit grey, black at the lowest point and white at the highest; the script prints both heights.
"""

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.transform import Affine
from rasterio.warp import Resampling, reproject, transform as warp_points
from rasterio.windows import Window, from_bounds

# planetarymaps.usgs.gov redirects to this bucket; GDAL reads the bucket directly, which is much faster
MIRROR = ("https://planetarymaps.usgs.gov/mosaic/", "https://asc-pds-services.s3.us-west-2.amazonaws.com/mosaic/")
# the grids are stored a row at a time, uncompressed: read only the part of each row we need, not whole rows
GDAL = {"GTIFF_DIRECT_IO": True, "GDAL_DISABLE_READDIR_ON_OPEN": "EMPTY_DIR", "GDAL_HTTP_MAX_RETRY": 5,
        "GDAL_HTTP_RETRY_DELAY": 2}


def local_map(src_crs: CRS, lon: float, lat: float) -> CRS:
    """A flat map in metres centred on (lon, lat), on the same body as the grid."""
    radius = src_crs.to_dict()["R"]                     # the USGS grids are on a sphere
    return CRS.from_proj4(f"+proj=aeqd +lat_0={lat} +lon_0={lon} +R={radius} +units=m +no_defs")


def heightmap(source: str, lon: float, lat: float, size_km: tuple[float, float],
              width: int = 900) -> tuple[np.ndarray, float]:
    """Heights in metres on a square-pixel grid around (lon, lat); returns the grid and its pixel size in m."""
    if source.startswith(MIRROR[0]):
        source = MIRROR[1] + source[len(MIRROR[0]):]
    lon = (lon + 180) % 360 - 180
    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)
    dst = Affine(pixel, 0, -cols * pixel / 2, 0, -pixel, rows * pixel / 2)

    with rasterio.Env(**GDAL), rasterio.open(source) as src:
        flat = local_map(src.crs, lon, lat)
        # the source area: the map's edge points in the grid's coordinates, plus a margin
        xs = np.r_[np.linspace(-1, 1, 21), np.ones(21), np.linspace(1, -1, 21), -np.ones(21)] * cols * pixel / 2
        ys = np.r_[np.ones(21), np.linspace(1, -1, 21), -np.ones(21), np.linspace(-1, 1, 21)] * rows * pixel / 2
        sx, sy = warp_points(flat, src.crs, xs, ys)
        win = from_bounds(min(sx), min(sy), max(sx), max(sy), src.transform)
        src_pixel = abs(src.transform.e) * (math.pi / 180 * flat.to_dict()["R"] if src.crs.is_geographic else 1)
        overviews = src.overviews(1)
        factor = next((f for f in reversed(overviews) if src_pixel * f <= pixel / 2), 1)

    level = {"overview_level": overviews.index(factor)} if factor > 1 else {}
    with rasterio.Env(**GDAL), rasterio.open(source, **level) as src:
        win = Window(win.col_off / factor - 2, win.row_off / factor - 2, win.width / factor + 4,
                     win.height / factor + 4).round_offsets().round_lengths()
        z = src.read(1, window=win, masked=True).astype("float32")
        z = (z * src.scales[0] + src.offsets[0]).filled(np.nan)               # LOLA stores half-metres
        out = np.full((rows, cols), np.nan, "float32")
        reproject(z, out, src_transform=src.window_transform(win), src_crs=src.crs, src_nodata=np.nan,
                  dst_transform=dst, dst_crs=flat, dst_nodata=np.nan,
                  resampling=Resampling.average if src_pixel * factor < pixel else Resampling.bilinear)
    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, pixel


def png16(z: np.ndarray, path: str) -> tuple[float, float]:
    """Save heights as a 16-bit greyscale PNG, lowest = black, highest = white."""
    lo, hi = float(z.min()), float(z.max())
    px = np.round((z - lo) / (hi - lo) * 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", z.shape[1], z.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""))
    return lo, hi


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("source")
    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)")
    a = ap.parse_args()
    z, pixel = heightmap(a.source, *a.at, (a.size[0], a.size[-1]), a.width)
    lo, hi = png16(z, 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), black = {lo:.0f} m, white = {hi:.0f} m ({hi - lo:.0f} m)")
