#!/usr/bin/env python3
"""Build local height + color assets for the Go Around Cape Town 3D terrain demo.

Source: Copernicus DEM GLO-30 (1-arc-second DSM), WGS84.
Licence: Copernicus Licence (free use with attribution).
© DLR e.V. and Airbus Defence and Space, provided by ESA / Copernicus Programme.
"""

from __future__ import annotations

import json
import math
from pathlib import Path

import numpy as np
import tifffile
from PIL import Image

ROOT = Path(__file__).resolve().parent
OUT = ROOT / "assets"
OUT.mkdir(exist_ok=True)

# Cape Town / Table Mountain / FACT / Cape Peninsula
WEST, EAST = 18.22, 18.70
NORTH, SOUTH = -33.72, -34.40

TILES = [
    # (path, tie_lon, tie_lat)  pixel (0,0) = top-left, PixelIsPoint
    ("/tmp/dem/copernicus_S34_E018.tif", 18.0, -33.0),
    ("/tmp/dem/copernicus_S35_E018.tif", 18.0, -34.0),
]
SCALE = 1.0 / 3600.0  # degrees per pixel

# Output texture / mesh resolution
TEX_LONG = 1800  # long side (south–north) in pixels
MESH_LONG = 520  # long side vertices

# Hypsometric ramp: elevation metres -> RGB 0-1, navy to gold
RAMP = [
    (-10.0, (7, 12, 20)),
    (0.0, (8, 16, 28)),
    (2.0, (10, 20, 36)),
    (15.0, (12, 24, 44)),
    (40.0, (14, 30, 54)),
    (80.0, (18, 40, 68)),
    (140.0, (24, 52, 84)),
    (220.0, (36, 68, 96)),
    (320.0, (58, 84, 100)),
    (450.0, (92, 102, 86)),
    (600.0, (130, 118, 68)),
    (750.0, (170, 140, 52)),
    (900.0, (201, 164, 48)),
    (1000.0, (220, 186, 78)),
    (1100.0, (236, 214, 140)),
    (1300.0, (245, 230, 180)),
]


def load_window(path: str, tie_lon: float, tie_lat: float, west, east, north, south):
    arr = tifffile.imread(path)
    rows, cols = arr.shape
    # pixel centres: lon = tie_lon + c*SCALE, lat = tie_lat - r*SCALE
    c0 = int(math.floor((west - tie_lon) / SCALE))
    c1 = int(math.ceil((east - tie_lon) / SCALE)) + 1
    r0 = int(math.floor((tie_lat - north) / SCALE))
    r1 = int(math.ceil((tie_lat - south) / SCALE)) + 1
    c0c, c1c = max(0, c0), min(cols, c1)
    r0c, r1c = max(0, r0), min(rows, r1)
    if c0c >= c1c or r0c >= r1c:
        return None
    window = arr[r0c:r1c, c0c:c1c].astype(np.float32)
    # Absolute row/col in a mosaic whose origin is lon=WEST? We'll return
    # the geographic coordinates of the window's first pixel centre.
    origin_lon = tie_lon + c0c * SCALE
    origin_lat = tie_lat - r0c * SCALE
    return window, origin_lon, origin_lat


def mosaic(west, east, north, south):
    pieces = []
    for path, tie_lon, tie_lat in TILES:
        got = load_window(path, tie_lon, tie_lat, west, east, north, south)
        if got is None:
            print(f"  skip (no overlap): {path}")
            continue
        pieces.append(got)
        print(f"  loaded {path}: {got[0].shape} origin=({got[1]:.6f},{got[2]:.6f})")

    # Mosaic into a regular grid covering the requested bbox (pixel centres)
    # Use the first piece's alignment; all tiles share the same 1-arcsec grid
    # anchored at integer degrees.
    # Grid columns whose centres are in [west, east], rows in [north, south]
    # We'll build from min origin.
    lons0 = [p[1] for p in pieces]
    lats0 = [p[2] for p in pieces]
    # Determine global col/row indices relative to (west-aligned grid on the 1" mesh)
    # Use an origin at lon=18, lat=-33 (S34 tile top-left) as index 0,0 of a virtual grid.
    base_lon, base_lat = 18.0, -33.0

    def to_idx(lon, lat):
        c = int(round((lon - base_lon) / SCALE))
        r = int(round((base_lat - lat) / SCALE))
        return r, c

    # requested window in virtual indices (inclusive start, exclusive end)
    r0, c0 = to_idx(west, north)
    # For the end, use the last pixel whose centre is <= east / >= south
    r1 = int(math.floor((base_lat - south) / SCALE)) + 1
    c1 = int(math.floor((east - base_lon) / SCALE)) + 1
    # clamp to available data (18..19 E, -33..-35 S) → r of S34 starts at 0, S35 at 3600
    height = r1 - r0
    width = c1 - c0
    mosaic_arr = np.full((height, width), np.nan, dtype=np.float32)
    for arr, olon, olat in pieces:
        pr0, pc0 = to_idx(olon, olat)
        pr0 -= r0
        pc0 -= c0
        h, w = arr.shape
        rs, cs = max(0, pr0), max(0, pc0)
        re, ce = min(height, pr0 + h), min(width, pc0 + w)
        srs, scs = rs - pr0, cs - pc0
        sre, sce = srs + (re - rs), scs + (ce - cs)
        mosaic_arr[rs:re, cs:ce] = arr[srs:sre, scs:sce]

    # Geographic extent of pixel centres and of the outer edges (half a pixel)
    lon_c0 = base_lon + (c0) * SCALE
    lat_c0 = base_lat - (r0) * SCALE
    lon_c1 = base_lon + (c1 - 1) * SCALE
    lat_c1 = base_lat - (r1 - 1) * SCALE
    extent = {
        "west": lon_c0 - SCALE / 2,
        "east": lon_c1 + SCALE / 2,
        "north": lat_c0 + SCALE / 2,
        "south": lat_c1 - SCALE / 2,
        "lon_first": lon_c0,
        "lat_first": lat_c0,
        "lon_last": lon_c1,
        "lat_last": lat_c1,
    }
    return mosaic_arr, extent


def clean_elev(z: np.ndarray) -> np.ndarray:
    out = z.copy()
    bad = ~np.isfinite(out) | (out < -50) | (out > 3000)
    out[bad] = np.nan
    # Treat remaining nan as ocean
    out = np.where(np.isnan(out), 0.0, out)
    # Flatten true water / slight negative coastal noise to a sea plane
    out = np.where(out < 0.25, 0.0, out)
    return out.astype(np.float32)


def resize(arr: np.ndarray, new_h: int, new_w: int, order_max_blend: bool = False) -> np.ndarray:
    """Area-average downsample (or bilinear-ish via PIL)."""
    img = Image.fromarray(arr, mode="F")
    # Image.Resampling.BOX is a good area filter for downsample
    out = img.resize((new_w, new_h), resample=Image.Resampling.BOX)
    return np.array(out, dtype=np.float32)


def hillshade(z: np.ndarray, dx: float, dy: float, azimuth=318.0, altitude=36.0) -> np.ndarray:
    """Horn 1981 hillshade, 0..1. dy is north-positive cell size in metres.
    z[row, col], row increases south, so dy for Horn's north-up gradient is -pixel_south.
    """
    # dz/dx: west to east, dz/dy: south to north (standard geographic)
    zpad = np.pad(z, 1, mode="edge")
    # Horn kernels
    dzdx = (
        (zpad[0:-2, 2:] + 2 * zpad[1:-1, 2:] + zpad[2:, 2:])
        - (zpad[0:-2, 0:-2] + 2 * zpad[1:-1, 0:-2] + zpad[2:, 0:-2])
    ) / (8.0 * dx)
    # row increases south, so northward derivative = - d/drow / dy_south
    dzdy_south = (
        (zpad[2:, 0:-2] + 2 * zpad[2:, 1:-1] + zpad[2:, 2:])
        - (zpad[0:-2, 0:-2] + 2 * zpad[0:-2, 1:-1] + zpad[0:-2, 2:])
    ) / (8.0 * dy)
    dzdy = -dzdy_south  # northward

    slope = np.arctan(np.hypot(dzdx, dzdy))
    aspect = np.arctan2(dzdy, -dzdx)  # 0 = east? atan2(north, west-origin)...
    # GDAL: aspect = atan2(dzdy, -dzdx); 0 is east? We'll use illumination vector instead.

    az = math.radians(azimuth)
    alt = math.radians(altitude)
    # Light vector: azimuth measured clockwise from north
    lx = math.sin(az) * math.cos(alt)  # east
    ly = math.cos(az) * math.cos(alt)  # north
    lz = math.sin(alt)

    # Surface normal (unnormalized): (-dzdx, -dzdy, 1) in (east, north, up)
    nlen = np.sqrt(dzdx * dzdx + dzdy * dzdy + 1.0)
    nx, ny, nz = -dzdx / nlen, -dzdy / nlen, 1.0 / nlen
    hs = np.clip(nx * lx + ny * ly + nz * lz, 0.0, 1.0)
    return hs.astype(np.float32)


def colorize(z: np.ndarray, hs: np.ndarray) -> np.ndarray:
    elevs = np.array([p[0] for p in RAMP], dtype=np.float32)
    cols = np.array([p[1] for p in RAMP], dtype=np.float32) / 255.0
    # interpolate each channel
    rgb = np.empty(z.shape + (3,), dtype=np.float32)
    for i in range(3):
        rgb[..., i] = np.interp(z, elevs, cols[:, i])

    # Force ocean to a clean deep navy (no gold leak)
    ocean = z <= 0.25
    rgb[ocean] = np.array([7, 14, 26], dtype=np.float32) / 255.0

    # Soft lighting: lift midtones, gold highlights, navy shadows
    hs_s = np.clip(hs, 0, 1)
    # Shadows deepen toward navy, highlights toward gold
    shadow = np.array([4, 8, 16], dtype=np.float32) / 255.0
    highlight = np.array([240, 214, 130], dtype=np.float32) / 255.0
    # Base * (0.28 + 0.85*hs)
    lit = rgb * (0.28 + 0.85 * hs_s)[..., None]
    # Overlay-like highlight on sun-facing slopes, stronger at high elevation
    hi = np.clip((hs_s - 0.62) / 0.38, 0, 1) ** 1.2
    hi = hi * np.clip((z - 80.0) / 700.0, 0.0, 1.0)
    lit = lit + highlight * (0.22 * hi)[..., None]
    # Shadow crush
    sh = np.clip((0.35 - hs_s) / 0.35, 0, 1)
    lit = lit * (1.0 - 0.45 * sh)[..., None] + shadow * (0.18 * sh)[..., None]

    # Ocean: very soft shade so it isn't a flat sticker, but stays calm
    if ocean.any():
        ocean_base = np.array([8, 16, 30], dtype=np.float32) / 255.0
        ocean_hi = np.array([22, 40, 64], dtype=np.float32) / 255.0
        ohs = 0.35 + 0.65 * hs_s
        oc = ocean_base * ohs[..., None] + ocean_hi * (0.15 * np.clip(hs_s - 0.5, 0, 1))[..., None]
        lit[ocean] = oc[ocean]
        # Soft shoreline (a few pixels of slightly lighter water)
        # dilate land a little via max filter on a mask
        land = (~ocean).astype(np.uint8)
        from numpy.lib.stride_tricks import sliding_window_view

        # cheap 3x3 max
        landp = np.pad(land, 1, mode="edge")
        near = np.zeros_like(land, dtype=bool)
        for dr in (-1, 0, 1):
            for dc in (-1, 0, 1):
                if dr == 0 and dc == 0:
                    continue
                near |= landp[1 + dr : 1 + dr + land.shape[0], 1 + dc : 1 + dc + land.shape[1]].astype(bool)
        shore = ocean & near
        lit[shore] = lit[shore] * 0.7 + np.array([16, 32, 52], dtype=np.float32) / 255.0 * 0.3

    return np.clip(lit * 255.0, 0, 255).astype(np.uint8)


def main():
    print("Mosaicking Copernicus GLO-30 …")
    z, extent = mosaic(WEST, EAST, NORTH, SOUTH)
    print("  raw mosaic", z.shape, "nan%", float(np.isnan(z).mean()) * 100)
    z = clean_elev(z)
    print(
        f"  elev min={z.min():.2f} max={z.max():.2f} mean={z.mean():.2f} "
        f"p99={np.percentile(z,99):.1f}"
    )

    # World size in metres (WGS84 approx at mid-lat)
    mid_lat = 0.5 * (extent["north"] + extent["south"])
    m_per_deg_lat = 111_132.95 - 559.82 * math.cos(2 * math.radians(mid_lat)) + 1.175 * math.cos(4 * math.radians(mid_lat))
    m_per_deg_lon = (
        111_412.84 * math.cos(math.radians(mid_lat))
        - 93.5 * math.cos(3 * math.radians(mid_lat))
    )
    world_w = (extent["east"] - extent["west"]) * m_per_deg_lon
    world_h = (extent["north"] - extent["south"]) * m_per_deg_lat
    dx = world_w / z.shape[1]
    dy = world_h / z.shape[0]
    print(f"  extent {extent}")
    print(f"  world {world_w/1000:.2f} km x {world_h/1000:.2f} km, pixel {dx:.1f}m x {dy:.1f}m")
    print(f"  mid-lat {mid_lat:.4f}")

    # Texture size
    aspect = z.shape[1] / z.shape[0]
    tex_h = TEX_LONG
    tex_w = int(round(TEX_LONG * aspect))
    z_tex = resize(z, tex_h, tex_w)
    hs = hillshade(z_tex, dx=world_w / tex_w, dy=world_h / tex_h)
    color = colorize(z_tex, hs)
    color_img = Image.fromarray(color, mode="RGB")
    color_path = OUT / "color.png"
    color_img.save(color_path, optimize=True)
    print(f"  wrote {color_path} {color.shape} {color_path.stat().st_size/1024:.0f} KB")

    # Also a flat preview (north up) for visual QA
    preview = color_img.copy()
    preview.save(OUT / "preview_northup.png", optimize=True)

    # Mesh heights
    mesh_h = MESH_LONG
    mesh_w = max(3, int(round(MESH_LONG * aspect)))
    z_mesh = resize(z, mesh_h, mesh_w)
    # Encode as uint16: 0 = 0m, 65535 = max*1.02 (tiny headroom)
    z_max = float(z.max())
    z_min = 0.0
    scale = (z_max * 1.02 - z_min) / 65535.0
    u16 = np.clip(np.rint((z_mesh - z_min) / scale), 0, 65535).astype("<u2")
    heights_path = OUT / "heights.bin"
    u16.tofile(heights_path)
    print(f"  wrote {heights_path} {u16.shape} {heights_path.stat().st_size/1024:.0f} KB  scale={scale:.6f}")

    # Landmark coordinates in world space: origin at geographic centre, +X east, +Z south
    def world_xz(lon, lat):
        x = ((lon - (extent["west"] + extent["east"]) / 2) * m_per_deg_lon)
        zc = (((extent["north"] + extent["south"]) / 2) - lat) * m_per_deg_lat
        return [round(x, 1), round(zc, 1)]

    landmarks = {
        "table_mountain": {"lon": 18.4096, "lat": -33.9628, **dict(zip(("x", "z"), world_xz(18.4096, -33.9628)))},
        "lions_head": {"lon": 18.3890, "lat": -33.9350, **dict(zip(("x", "z"), world_xz(18.3890, -33.9350)))},
        "devils_peak": {"lon": 18.4403, "lat": -33.9556, **dict(zip(("x", "z"), world_xz(18.4403, -33.9556)))},
        "fact": {"lon": 18.6017, "lat": -33.9648, **dict(zip(("x", "z"), world_xz(18.6017, -33.9648)))},
        "cape_point": {"lon": 18.4970, "lat": -34.3568, **dict(zip(("x", "z"), world_xz(18.4970, -34.3568)))},
        "robben_island": {"lon": 18.3660, "lat": -33.8070, **dict(zip(("x", "z"), world_xz(18.3660, -33.8070)))},
        "hout_bay": {"lon": 18.3550, "lat": -34.0480, **dict(zip(("x", "z"), world_xz(18.3550, -34.0480)))},
    }

    meta = {
        "source": "Copernicus DEM GLO-30 (ESA / Copernicus Programme)",
        "source_tiles": [
            "Copernicus_DSM_COG_10_S34_00_E018_00_DEM",
            "Copernicus_DSM_COG_10_S35_00_E018_00_DEM",
        ],
        "licence": "Copernicus Licence — free use with attribution. © DLR e.V. and Airbus Defence and Space, provided by ESA / Copernicus Programme.",
        "attribution": "Elevation: Copernicus DEM GLO-30 © DLR e.V. & Airbus, provided by ESA / Copernicus Programme",
        "crs": "WGS84",
        "bbox": {"west": WEST, "east": EAST, "north": NORTH, "south": SOUTH},
        "extent": extent,
        "world": {
            "width_m": round(world_w, 1),
            "height_m": round(world_h, 1),
            "mid_lat": mid_lat,
        },
        "elevation": {"min_m": z_min, "max_m": z_max, "u16_scale_m": scale, "u16_offset_m": z_min},
        "mesh": {"cols": mesh_w, "rows": mesh_h},
        "texture": {"width": tex_w, "height": tex_h},
        "landmarks": landmarks,
    }
    meta_path = OUT / "meta.json"
    meta_path.write_text(json.dumps(meta, indent=2))
    print(f"  wrote {meta_path}")
    print("  landmarks:")
    for k, v in landmarks.items():
        # sample elev near landmark
        print(f"    {k}: x={v['x']:.0f} z={v['z']:.0f}")


if __name__ == "__main__":
    main()
