"""
Lesson 6 figures: the same port at Sentinel-1 10 m and at ICEYE spotlight resolution.

Data
- ICEYE SAR Open Dataset (CC BY 4.0): spotlight scene of the Port of Hamburg,
  26 Aug 2026, read from the public S3 bucket (no account needed).
- Sentinel-1 RTC (gamma0) from Microsoft Planetary Computer, the pass on the same day.
- OpenStreetMap outlines (ODbL) for the container terminal and floating docks,
  fetched once from the Overpass API and cached in cache/osm_hh.json.

Writes ../site/img/09_iceye_scene.png, ../site/img/10_iceye_zoom.png and iceye_facts.json.
Run:  ../../../../.venv_sar/Scripts/python build_iceye_figs.py
"""
import json
import pathlib
import sys
import urllib.parse
import urllib.request

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from affine import Affine
from pyproj import Transformer

sys.path.insert(0, str(pathlib.Path(__file__).parent))
import iceye_lib as il
from sarlib import read_window, search

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "img"   # site/img when run from site/code
OUT.mkdir(parents=True, exist_ok=True)
INK = "#1d2733"
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 10,
                     "axes.titlesize": 11, "axes.titleweight": "bold",
                     "figure.dpi": 110, "savefig.dpi": 150})

STAC = ("https://iceye-open-data-catalog.s3.amazonaws.com/stac-items/2026/08/"
        "ICEYE_U1X0DE_20260826T205215Z_10395144_X61_SLH.json")
BB = [9.915, 53.517, 10.013, 53.574]          # Sentinel-1 window (lon/lat)
BOX = 600.0                                    # zoom box side, metres
ZOOMS = {  # name: (lon, lat) of the box centre, OSM outlines drawn in that box
    "Container Terminal Tollerort": ((9.9506, 53.5333), ("Container Terminal Tollerort",)),
    "Blohm+Voss floating docks": ((9.9556, 53.5411), ("Dock 6", "Dock 11", "Dock 16")),
}
OSM_QUERY = ('[out:json][timeout:25];(way(around:700,53.5395,9.952)["seamark:type"="floating_dock"];'
             'way(around:400,53.53413,9.94873)[name="Container Terminal Tollerort"];);out geom tags;')
CREDIT = ("ICEYE Synthetic Aperture Radar (SAR) Open Dataset, (c) ICEYE, CC BY 4.0, scene "
          "ICEYE_U1X0DE_20260826T205215Z_10395144_X61_SLH; resampled, map-projected and annotated by David Reid.\n"
          "Contains modified Copernicus Sentinel data (2026), via Microsoft Planetary Computer. "
          "Outlines (c) OpenStreetMap contributors, ODbL.")


def osm():
    f = HERE / "cache" / "osm_hh.json"
    if not f.exists():
        data = urllib.parse.urlencode({"data": OSM_QUERY}).encode()
        req = urllib.request.Request("https://overpass-api.de/api/interpreter", data=data,
                                     headers={"User-Agent": "sar-training-module/1.0"})
        with urllib.request.urlopen(req, timeout=60) as r:
            f.write_bytes(r.read())
    els = json.loads(f.read_text(encoding="utf-8"))["elements"]
    return [(e["tags"].get("name", ""), [(p["lon"], p["lat"]) for p in e["geometry"]]) for e in els]


def s1_geometry(lon, lat):
    """Incidence angle at (lon, lat) and look azimuth of the same-day Sentinel-1 pass, from its GRD annotation."""
    import xml.etree.ElementTree as ET
    from scipy.interpolate import griddata
    f = HERE / "cache" / "s1_20260826_iw-vv.xml"
    if not f.exists():
        grd = search("sentinel-1-grd", BB, "2026-08-26/2026-08-26")[0]
        href = grd.assets["schema-product-vv"].href.replace("annotation/rfi/rfi-iw-vv.xml", "annotation/iw-vv.xml")
        with urllib.request.urlopen(href, timeout=120) as r:
            f.write_bytes(r.read())
    root = ET.fromstring(f.read_bytes())
    heading = float(root.find(".//platformHeading").text)
    pts = [(float(g.find("longitude").text), float(g.find("latitude").text), float(g.find("incidenceAngle").text))
           for g in root.iter("geolocationGridPoint")]
    xy = np.array([(a, b) for a, b, _ in pts]); z = np.array([c for _, _, c in pts])
    inc = float(griddata(xy, z, [(lon, lat)], method="linear")[0])
    return inc, (heading + 90) % 360  # Sentinel-1 looks to the right of its track


def clean(ax):
    ax.set_xticks([]); ax.set_yticks([])
    for s in ax.spines.values():
        s.set_visible(False)


def bar(ax, x0, y0, length, label):
    """Scale bar in map metres (axes use UTM extents)."""
    ax.plot([x0, x0 + length], [y0, y0], color="white", lw=3, solid_capstyle="butt")
    ax.text(x0 + length / 2, y0, label, color="white", ha="center", va="bottom", fontsize=8,
            fontweight="bold", bbox=dict(boxstyle="round,pad=0.2", fc="#000000aa", ec="none"))


def main():
    it = il.item(STAC)
    g = il.grd_meta(it)
    p = g["properties"]
    rpcd = p["iceye:rpc"]
    H, W = p["proj:shape"]
    href = it["assets"]["grd-cog"]["href"]
    HGT = float(p["iceye:average_scene_height"])

    s1 = search("sentinel-1-rtc", BB, "2026-08-26/2026-08-26")[0]
    vv, tr, crs = read_window(s1.assets["vv"].href, BB)
    vv[vv <= 0] = np.nan
    s1db = 10 * np.log10(vv)
    to_utm = Transformer.from_crs("EPSG:4326", crs, always_xy=True)

    # whole scene: 4x4-averaged ICEYE power (2 m), on a 10 m grid for alignment and a 2 m grid for display
    pw4 = il.read_power(href, 0, 0, H, W, 4)
    ice10 = il.to_map(pw4, rpcd, 0, 0, 4, tr, crs, vv.shape, HGT)
    a, b = s1db, 10 * np.log10(ice10)
    m = np.isfinite(a) & np.isfinite(b)
    best = (-1, 0, 0)
    for dy in range(-4, 5):
        for dx in range(-4, 5):
            P = 4
            aa = a[P:-P, P:-P]
            bs = b[P - dy:b.shape[0] - P - dy, P - dx:b.shape[1] - P - dx]
            mm = np.isfinite(aa) & np.isfinite(bs)
            c = float(np.corrcoef(aa[mm], bs[mm])[0, 1])
            if c > best[0]:
                best = (c, dy, dx)
    tr2 = Affine(2, 0, tr.c, 0, -2, tr.f)
    ice2 = il.to_map(pw4, rpcd, 0, 0, 4, tr2, crs, (vv.shape[0] * 5, vv.shape[1] * 5), HGT)
    ice2db = 10 * np.log10(ice2)
    lo, hi = [float(v) for v in np.nanpercentile(ice2db, [2, 99.5])]

    ext = (tr.c, tr.c + 10 * vv.shape[1], tr.f - 10 * vv.shape[0], tr.f)
    outlines = [(n, np.array([to_utm.transform(x, y) for x, y in pts])) for n, pts in osm()]

    # ---------------- figure 09: the whole scene
    fig, axs = plt.subplots(1, 2, figsize=(13, 6.6))
    axs[0].imshow(s1db, cmap="gray", vmin=-20, vmax=5, extent=ext, interpolation="nearest")
    axs[0].set_title(f"Sentinel-1, 10 m pixels, {s1.properties['datetime'][:10]} "
                     f"{s1.properties['datetime'][11:16]} UTC")
    axs[1].imshow(ice2db, cmap="gray", vmin=lo, vmax=hi, extent=ext)
    axs[1].set_facecolor("#2a2f36")  # outside the ICEYE footprint
    axs[1].set_title(f"ICEYE spotlight, averaged to 2 m for display, {p['datetime'][:10]} {p['datetime'][11:16]} UTC")
    for k, (name, ((lon, lat), _)) in enumerate(ZOOMS.items(), 1):
        x, y = to_utm.transform(lon, lat)
        for ax in axs:
            ax.add_patch(plt.Rectangle((x - BOX / 2, y - BOX / 2), BOX, BOX, fill=False, ec="#ffd84d", lw=2))
            ax.text(x - BOX / 2, y + BOX / 2 + 40, str(k), color="#ffd84d", fontsize=13, fontweight="bold",
                    bbox=dict(boxstyle="round,pad=0.2", fc="#000000b0", ec="none"))
    for ax in axs:
        ax.set_xlim(ext[0], ext[1]); ax.set_ylim(ext[2], ext[3])
        clean(ax)
        bar(ax, ext[0] + 250, ext[2] + 300, 1000, "1 km")
    fig.suptitle("Port of Hamburg on one day: free 10 m radar beside an ICEYE spotlight scene from ICEYE's open data",
                 fontsize=12, fontweight="bold", color=INK, x=0.01, ha="left")
    fig.text(0.995, 0.005, CREDIT, ha="right", va="bottom", fontsize=7.5, color="#5b6876")
    fig.tight_layout(rect=(0, 0.04, 1, 0.95))
    fig.savefig(OUT / "09_iceye_scene.png"); plt.close(fig)

    # ---------------- figure 10: two zoom boxes at full resolution
    fig, axs = plt.subplots(2, 2, figsize=(12, 12.4))
    zoom_facts = {}
    for k, (name, ((lon, lat), keep)) in enumerate(ZOOMS.items()):
        x, y = to_utm.transform(lon, lat)
        x0, y1 = x - BOX / 2, y + BOX / 2
        n = int(BOX / 0.5)
        t05 = Affine(0.5, 0, x0, 0, -0.5, y1)
        zext = (x0, x0 + BOX, y1 - BOX, y1)
        r, c = il.latlon_to_px(rpcd, lon, lat, HGT)
        half = int(BOX / 0.5 * 0.85)
        r0, c0 = max(r - half, 0), max(c - half, 0)
        pw = il.read_power(href, r0, c0, min(2 * half, H - r0), min(2 * half, W - c0), 1)
        ice = 10 * np.log10(il.to_map(pw, rpcd, r0, c0, 1, t05, crs, (n, n), HGT))
        zl, zh = [float(v) for v in np.nanpercentile(ice, [2, 99.7])]
        cs, rs, kk = int((zext[0] - tr.c) / 10), int((tr.f - zext[3]) / 10), int(BOX / 10)
        sl, sh = [float(v) for v in np.nanpercentile(s1db[rs:rs + kk, cs:cs + kk], [2, 99.7])]
        axs[k, 0].imshow(s1db, cmap="gray", vmin=sl, vmax=sh, extent=ext, interpolation="nearest")
        axs[k, 1].imshow(ice, cmap="gray", vmin=zl, vmax=zh, extent=zext, interpolation="nearest")
        axs[k, 0].set_title(f"{k + 1}. Sentinel-1: about 20 m resolution, 10 m grid", loc="left", fontsize=10)
        axs[k, 1].set_title(f"{k + 1}. ICEYE: 1.4 x 1.0 m resolution, 0.5 m grid", loc="left", fontsize=10)
        for ax in axs[k]:
            for oname, xy in outlines:
                if oname in keep and (xy[:, 0].max() > zext[0] and xy[:, 0].min() < zext[1]
                        and xy[:, 1].max() > zext[2] and xy[:, 1].min() < zext[3]):
                    ax.plot(xy[:, 0], xy[:, 1], color="#4dd2ff", lw=1.3, ls="--")
            ax.set_xlim(zext[0], zext[1]); ax.set_ylim(zext[2], zext[3])
            clean(ax)
            bar(ax, zext[0] + 30, zext[2] + 35, 100, "100 m")
        zoom_facts[name] = {"lon": lon, "lat": lat, "box_m": BOX,
                            "s1_pixels_across": int(BOX / 10), "iceye_pixels_across": n}
    fig.suptitle("(1) Container Terminal Tollerort, (2) Blohm+Voss floating docks. Dashed blue = OpenStreetMap outlines.\n"
                 "Each panel has its own brightness stretch; compare shapes, not grey levels",
                 fontsize=12, fontweight="bold", color=INK, x=0.01, ha="left")
    fig.text(0.995, 0.004, CREDIT, ha="right", va="bottom", fontsize=7.5, color="#5b6876")
    fig.tight_layout(rect=(0, 0.03, 1, 0.945))
    fig.savefig(OUT / "10_iceye_zoom.png"); plt.close(fig)

    s1_inc, s1_look = s1_geometry(p["proj:centroid"]["lon"], p["proj:centroid"]["lat"])
    t_ice = p["datetime"]; t_s1 = s1.properties["datetime"]
    from datetime import datetime
    dh = (datetime.fromisoformat(t_ice.replace("Z", "+00:00"))
          - datetime.fromisoformat(t_s1.replace("Z", "+00:00"))).total_seconds() / 3600
    facts = {
        "iceye": {"id": it["id"], "datetime_utc": t_ice, "platform": p["platform"],
                  "mode": p["sar:instrument_mode"], "processing_mode": p["iceye:processing_mode"],
                  "band": p["sar:frequency_band"], "center_frequency_hz": p["sar:center_frequency"],
                  "range_bandwidth_hz": g.get("iceye:pulse_bandwidth", p.get("iceye:pulse_bandwidth")),
                  "polarization": p["sar:polarizations"], "orbit_state": p["sat:orbit_state"],
                  "look_side": p["sar:observation_direction"],
                  "incidence_deg": round(p["view:incidence_angle"], 1),
                  "resolution_range_m": round(p["sar:resolution_range"], 2),
                  "resolution_azimuth_m": round(p["sar:resolution_azimuth"], 2),
                  "pixel_spacing_m": round(p["sar:pixel_spacing_range"], 2),
                  "extent_km": [round(p["iceye:extent_range"] / 1000, 1), round(p["iceye:extent_azimuth"] / 1000, 1)],
                  "rpc_height_m": HGT, "licence": "CC BY 4.0"},
        "sentinel1": {"id": s1.id, "datetime_utc": t_s1, "orbit_state": s1.properties.get("sat:orbit_state"),
                      "relative_orbit": s1.properties.get("sat:relative_orbit")},
        "hours_between": round(dh, 1),
        "alignment": {"best_corr": round(best[0], 3), "shift_rows_10m": best[1], "shift_cols_10m": best[2],
                      "offset_m": round(10 * float(np.hypot(best[1], best[2]))),
                      "note": "integer 10 m shifts only; not corrected in the figures"},
        "geometry": {"s1_incidence_deg": round(s1_inc, 1), "s1_look_azimuth_deg": round(s1_look),
                     "iceye_look_azimuth_deg": round((p["view:azimuth"] + 180) % 360),
                     "look_difference_deg": round(abs(((p["view:azimuth"] + 180) - s1_look + 180) % 360 - 180)),
                     "iceye_layover_per_m_height": round(1 / np.tan(np.radians(p["view:incidence_angle"])), 2),
                     "s1_layover_per_m_height": round(1 / np.tan(np.radians(s1_inc)), 2),
                     "range_offset_per_10m_height_error_m": round(10 / np.tan(np.radians(p["view:incidence_angle"])))},
        "resolution_cells_per_s1_cell": round((20 * 22) / (p["sar:resolution_range"] * p["sar:resolution_azimuth"])),
        "pixels_per_s1_pixel": int((10 / 0.5) ** 2),
        "zooms": zoom_facts,
        "osm_long_axis_m": {n: round(float(np.ptp((xy - xy.mean(0)) @ np.linalg.svd(xy - xy.mean(0))[2][0])))
                            for n, xy in outlines if n.startswith("Dock")},
    }
    (HERE / "iceye_facts.json").write_text(json.dumps(facts, indent=1), encoding="utf-8")
    print(json.dumps(facts, indent=1))


if __name__ == "__main__":
    main()
