"""
Figures 11-16 for the expanded course (lessons on image formation, wavelength, brightness,
polarisation, coherence and phase). Real data: Sentinel-1 RTC (Planetary Computer), the ALOS-2
PALSAR-2 annual mosaic (JAXA, via Planetary Computer) and the Global Seasonal Sentinel-1
Interferometric Coherence and Backscatter Data Set (Kellndorfer et al., AWS open data).
Figures 11 and 16 are schematics/simulations and say so on the figure.
Writes PNGs to ../site/img and every quoted number to course_facts.json.

Run:  ../../../../.venv_sar/Scripts/python build_course_figs.py
"""
import json
import pathlib
import sys
import xml.etree.ElementTree as ET  # local, cached ESA annotation file only

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import rasterio
from matplotlib.patches import Arc, Ellipse, FancyArrowPatch
from pyproj import Transformer
from rasterio.warp import transform_bounds
from rasterio.windows import from_bounds

sys.path.insert(0, str(pathlib.Path(__file__).parent))
from sarlib import CACHE, lonlat_to_px, s1_db, search, to_byte

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "img"
FACTS = {}
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 10, "axes.titlesize": 11,
                     "axes.titleweight": "bold", "figure.dpi": 110, "savefig.dpi": 150})
INK, MUTED, ACC = "#1d2733", "#5b6876", "#0b6e99"
C_LIGHT = 299792458.0
BB = [13.15, 52.42, 13.70, 52.56]  # Berlin, as in figure 02
MARKS = {"lake": (13.645, 52.438), "forest": (13.225, 52.485), "city": (13.400, 52.520), "field": (13.403, 52.473)}
NAMES = {"lake": "Müggelsee (lake)", "forest": "Grunewald (forest)", "city": "Mitte (city)", "field": "Tempelhof (field)"}
S1_CREDIT = "Contains modified Copernicus Sentinel data (2026), via Microsoft Planetary Computer."
PALSAR_CREDIT = "L-band: the original data used for this product have been supplied by JAXA's Global PALSAR-2/PALSAR Mosaic (2021, (c) JAXA)."
COH_CREDIT = ("Coherence: Global Seasonal Sentinel-1 Interferometric Coherence and Backscatter Data Set "
              "(Kellndorfer et al. 2022), CC BY 4.0. Contains modified Copernicus Sentinel data (2019-2020).")


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


def credit(fig, text, y=0.005):
    fig.text(0.995, y, text, ha="right", va="bottom", fontsize=6.5, color="#6b7785")


def scalebar(ax, px_m, length_m, label, loc=(0.03, 0.07)):
    x0, y0 = loc
    w = ax.get_xlim()[1] - ax.get_xlim()[0]
    frac = (length_m / px_m) / w
    ax.plot([x0, x0 + frac], [y0, y0], transform=ax.transAxes, color="white", lw=3, solid_capstyle="butt")
    ax.text(x0 + frac / 2, y0 + 0.03, label, transform=ax.transAxes, color="white", ha="center", va="bottom",
            fontsize=8, fontweight="bold", bbox=dict(boxstyle="round,pad=0.2", fc="#000000aa", ec="none"))


def read_geo(href, bb, out_shape=None, cache_key=None):
    """Window of a lon/lat bbox from any COG/GeoTIFF; optional resample to out_shape. Cached."""
    if cache_key and (CACHE / cache_key).exists():
        return np.load(CACHE / cache_key)
    with rasterio.open(href) as src:
        b = transform_bounds("EPSG:4326", src.crs, *bb, densify_pts=21)
        win = from_bounds(*b, transform=src.transform).round_offsets().round_lengths()
        kw = {}
        if out_shape:
            from rasterio.enums import Resampling
            kw = {"out_shape": out_shape, "resampling": Resampling.bilinear}
        a = src.read(1, window=win, boundless=True, fill_value=0, **kw).astype("float64")
    if cache_key:
        np.save(CACHE / cache_key, a)
    return a


def box_median(arr, bb, lon, lat, half_m=150):
    """Median of a ~300 m box around lon/lat in an array that spans bb in lon/lat (plate carree)."""
    h, w = arr.shape
    c = (lon - bb[0]) / (bb[2] - bb[0]) * w
    r = (bb[3] - lat) / (bb[3] - bb[1]) * h
    mx = 111320 * np.cos(np.radians(lat)) * (bb[2] - bb[0]) / w
    my = 111320 * (bb[3] - bb[1]) / h
    hx, hy = max(1, round(half_m / mx)), max(1, round(half_m / my))
    c, r = int(c), int(r)
    return float(np.nanmedian(arr[r - hy:r + hy, c - hx:c + hx]))


def s1_item():
    items = [i for i in search("sentinel-1-rtc", BB, "2026-10-01/2026-11-21") if i.properties["sat:orbit_state"] == "descending"]
    orb = items[-1].properties["sat:relative_orbit"]
    return [i for i in items if i.properties["sat:relative_orbit"] == orb][-1]


# ------------------------------------------------------------- 11. how an image is built
def fig_formation():
    # Sentinel-1 numbers from the product annotation of the 26 Aug 2026 Hamburg GRD (cached by build_iceye_figs.py)
    x = ET.fromstring((HERE / "cache" / "s1_20260826_iw-vv.xml").read_bytes())
    bws = [float(e.text) for e in x.iter("totalBandwidth") if float(e.text) > 1e6]
    looks = [int(e.text) for e in x.iter("numberOfLooks")]
    f0 = float(next(x.iter("radarFrequency")).text)
    lam = C_LIGHT / f0
    slant = [C_LIGHT / (2 * b) for b in bws]
    FACTS["s1_formation"] = {"source": "S1 GRD annotation iw-vv.xml, 26 Aug 2026",
                             "range_bandwidth_mhz": [round(b / 1e6, 1) for b in bws],
                             "slant_range_resolution_m": [round(s, 2) for s in slant],
                             "grd_looks_range_azimuth": looks[:2], "radar_frequency_ghz": round(f0 / 1e9, 3),
                             "wavelength_cm": round(lam * 100, 2),
                             "antenna_length_m": 12.3,
                             "beam_footprint_km_at_850km": round(lam / 12.3 * 850, 1),
                             "stripmap_azimuth_res_m": round(12.3 / 2, 1),
                             "iceye_slant_res_m_300mhz": round(C_LIGHT / (2 * 300e6), 2)}

    fig, axs = plt.subplots(1, 2, figsize=(13, 5.2), gridspec_kw={"width_ratios": [1.15, 1]})
    # A: cross-section, looking along the track
    ax = axs[0]
    sat = np.array([0.0, 7.0])
    ax.plot([-0.5, 11.5], [0, 0], color="#6d5d3f", lw=2)
    ax.fill_between([-0.5, 11.5], -0.45, 0, color="#e9e1cf")
    ax.plot(*sat, marker="s", ms=13, color=INK)
    ax.text(sat[0] + 0.25, sat[1] + 0.25, "satellite\n(flying into the page)", fontsize=9, color=INK, va="bottom")
    ax.plot([0, 0], [0, 7], ls=":", color=MUTED, lw=1)
    near, far = 3.0, 10.0
    for gx in (near, far):
        ax.plot([sat[0], gx], [sat[1], 0], color=ACC, lw=1.2, alpha=0.7)
    ax.annotate("", xy=(far, -1.15), xytext=(near, -1.15), arrowprops=dict(arrowstyle="<->", color=INK, lw=1.2))
    ax.text((near + far) / 2, -1.3, "swath (Sentinel-1 IW: about 250 km)", ha="center", va="top", fontsize=9, color=INK)
    ax.text(near, 0.15, "near\nrange", ha="center", va="bottom", fontsize=8, color=MUTED)
    ax.text(far, 0.15, "far\nrange", ha="center", va="bottom", fontsize=8, color=MUTED)
    # two slant-range arcs around point P, showing slant vs ground spacing
    P = 6.0
    R1 = np.hypot(P - sat[0], sat[1])
    dR = 0.9
    for R in (R1, R1 + dR):
        th = np.linspace(np.radians(-58), np.radians(-40), 60)
        xs_, ys_ = sat[0] + R * np.cos(th), sat[1] + R * np.sin(th)
        keep = ys_ >= 0
        ax.plot(xs_[keep], ys_[keep], color="#c2410c", lw=1.4)
    g2 = np.sqrt((R1 + dR) ** 2 - sat[1] ** 2)
    ax.plot([P, g2], [0, 0], color="#c2410c", lw=5, solid_capstyle="butt")
    ax.text((P + g2) / 2, -0.08, "ground range\nresolution", ha="center", va="top", fontsize=8.5, color="#c2410c", fontweight="bold")
    u = np.array([np.cos(np.radians(-40.5)), np.sin(np.radians(-40.5))])
    q1, q2 = sat + R1 * u, sat + (R1 + dR) * u
    ax.annotate("", xy=tuple(q2), xytext=tuple(q1), arrowprops=dict(arrowstyle="<->", color="#c2410c", lw=1.4))
    ax.text(q2[0] + 0.35, q2[1] + 0.75, "slant range\nresolution = c / 2B", ha="left", va="bottom", fontsize=8.5, color="#c2410c", fontweight="bold")
    # incidence angle at P
    ang = np.degrees(np.arctan2(sat[1], sat[0] - P))  # direction from P to sat
    ax.plot([P, P], [0, 1.6], ls=":", color=MUTED, lw=1)
    ax.add_patch(Arc((P, 0), 2.2, 2.2, angle=0, theta1=90, theta2=ang, color=INK, lw=1.2))
    ax.text(P - 0.75, 1.75, "θ", fontsize=13, color=INK)
    ax.text(0.2, 3.3, "slant range R\n= c × echo time / 2", fontsize=9, color=ACC, rotation=-40)
    ax.set_xlim(-0.8, 11.8); ax.set_ylim(-2.0, 8.2); ax.set_aspect("equal"); clean(ax)
    ax.set_title("A. Across the track: range is measured by echo time", loc="left")
    ax.text(11.6, 7.9, "θ = incidence angle", ha="right", fontsize=9, color=INK)
    # B: from above, the synthetic aperture
    ax = axs[1]
    ax.annotate("", xy=(0.6, 9.3), xytext=(0.6, 0.4), arrowprops=dict(arrowstyle="->", color=INK, lw=1.6))
    ax.text(0.35, 4.9, "flight direction = azimuth", rotation=90, va="center", ha="center", fontsize=9, color=INK)
    tgt = (7.0, 5.0)
    ys = [2.4, 5.0, 7.6]
    for k, y in enumerate(ys):
        ax.plot(1.2, y, marker="s", ms=10, color=INK)
        ax.add_patch(Ellipse((7.0, y), 8.2, 5.7, fill=True, fc=(0.04, 0.43, 0.6, 0.07), ec=ACC, lw=1.2))
        ax.plot([1.35, 2.9], [y, y], color=ACC, lw=1, alpha=0.6)
    ax.text(1.5, ys[0] - 0.4, "first sees\nthe target", fontsize=7.5, color=MUTED, va="top", ha="left")
    ax.text(1.5, ys[2] + 0.4, "last sees\nthe target", fontsize=7.5, color=MUTED, va="bottom", ha="left")
    ax.plot(*tgt, marker="*", ms=17, color="#c2410c")
    ax.text(tgt[0] + 0.3, tgt[1] - 0.15, "target", fontsize=9, color="#c2410c", va="top")
    ax.annotate("", xy=(2.3, ys[2]), xytext=(2.3, ys[0]), arrowprops=dict(arrowstyle="<->", color="#c2410c", lw=1.4))
    ax.text(2.55, 11.2, "synthetic aperture: every echo from this stretch\nof the track is combined in processing",
            fontsize=8.5, color="#c2410c", va="bottom")
    ax.text(11.0, -1.45, "beam footprint on the ground: about 4 km along the track,\nfar wider across it (Sentinel-1)", fontsize=8.5, color=ACC, ha="right", va="top")
    ax.set_xlim(0, 11.3); ax.set_ylim(-2.6, 12.4); ax.set_aspect("equal"); clean(ax)
    ax.set_title("B. Along the track: the synthetic aperture", loc="left")
    fig.suptitle("How a radar image is built (schematic, not to scale)", fontsize=12, fontweight="bold", color=INK, x=0.01, ha="left")
    fig.tight_layout(rect=(0, 0.0, 1, 0.95))
    fig.savefig(OUT / "11_formation.png"); plt.close(fig)


# ------------------------------------------------------------- 12. wavelength: C-band vs L-band
def palsar(pol):
    it = search("alos-palsar-mosaic", BB, "2015-01-01/2021-12-31")[-1]
    dn = read_geo(it.assets[pol].href, BB, cache_key=f"palsar_{it.id}_{pol}.npy").copy()
    dn[dn <= 0] = np.nan
    return 10 * np.log10(dn ** 2) - 83.0, it


def s1_on_grid(item, pol, shape):
    """Sentinel-1 RTC resampled onto the PALSAR lon/lat grid, for same-footprint display and boxes."""
    href = item.assets[pol].href
    with rasterio.open(href) as src:
        crs = src.crs
    lin = read_geo(href, BB, cache_key=None) if False else None
    # read in native UTM then reproject to the lon/lat grid of BB
    from rasterio.warp import reproject, Resampling
    from rasterio.transform import from_bounds as tfb
    with rasterio.open(href) as src:
        b = transform_bounds("EPSG:4326", src.crs, *BB, densify_pts=21)
        win = from_bounds(*b, transform=src.transform).round_offsets().round_lengths()
        a = src.read(1, window=win, boundless=True, fill_value=0).astype("float32")
        tr = src.window_transform(win)
    a[a <= 0] = np.nan
    dst = np.full(shape, np.nan, dtype="float32")
    reproject(a, dst, src_transform=tr, src_crs=crs, dst_transform=tfb(*BB, shape[1], shape[0]),
              dst_crs="EPSG:4326", resampling=Resampling.average, src_nodata=np.nan, dst_nodata=np.nan)
    return 10 * np.log10(dst)


def fig_wavelength(it):
    hv, pit = palsar("HV")
    hh, _ = palsar("HH")
    vh = s1_on_grid(it, "vh", hv.shape)
    vv = s1_on_grid(it, "vv", hv.shape)
    med = {}
    for nm, arr in (("C_VV", vv), ("C_VH", vh), ("L_HH", hh), ("L_HV", hv)):
        med[nm] = {k: round(box_median(arr, BB, *v), 1) for k, v in MARKS.items()}
    contrast = {k: round(med[k]["forest"] - med[k]["field"], 1) for k in med}
    FACTS["wavelength"] = {"s1_item": it.id, "s1_date": it.properties["datetime"][:10], "palsar_item": pit.id,
                           "palsar_year": pit.properties["start_datetime"][:4], "palsar_gsd_m": pit.properties.get("gsd"),
                           "palsar_calibration": "gamma0 dB = 10*log10(DN^2) - 83.0", "box_medians_db": med,
                           "forest_minus_field_db": contrast}
    fig = plt.figure(figsize=(13, 8.6))
    gs = fig.add_gridspec(2, 2, width_ratios=[2.35, 1], hspace=0.16, wspace=0.42)
    for row, (arr, ttl) in enumerate(((vh, f"C-band (about 5.5 cm), Sentinel-1 VH, {it.properties['datetime'][:10]}"),
                                      (hv, f"L-band (about 24 cm), ALOS-2 PALSAR-2 HV, {pit.properties['start_datetime'][:4]} mosaic"))):
        ax = fig.add_subplot(gs[row, 0])
        ax.imshow(to_byte(arr, -28, -6), cmap="gray", aspect=1 / np.cos(np.radians(52.49)))
        for k in ("forest", "field"):
            lon, lat = MARKS[k]
            c = (lon - BB[0]) / (BB[2] - BB[0]) * arr.shape[1]; r = (BB[3] - lat) / (BB[3] - BB[1]) * arr.shape[0]
            ax.add_patch(plt.Rectangle((c - 10, r - 6), 20, 12, fill=False, color="#ffd84d", lw=1.5))
            ax.text(c + 15, r - 9, NAMES[k], color="#ffd84d", fontsize=9, fontweight="bold",
                    bbox=dict(boxstyle="round,pad=0.2", fc="#000000b0", ec="none"))
        clean(ax); ax.set_title(ttl + "  (same stretch: -28 to -6 dB)", loc="left", fontsize=10.5)
    ax = fig.add_subplot(gs[:, 1])
    cls = ["lake", "field", "forest", "city"]
    keys = [("C_VV", "C-band VV", "#9ec5d8"), ("C_VH", "C-band VH", ACC), ("L_HH", "L-band HH", "#f2b27a"), ("L_HV", "L-band HV", "#c2410c")]
    y = np.arange(len(cls))
    for j, (k, lab, col) in enumerate(keys):
        ax.barh(y + (j - 1.5) * 0.2, [med[k][c] + 32 for c in cls], left=-32, height=0.19, color=col, label=lab)
    ax.set_yticks(y); ax.set_yticklabels([NAMES[c] for c in cls]); ax.invert_yaxis()
    ax.set_xlabel("median backscatter in a 300 m box (dB)")
    ax.set_xlim(-32, 0)
    ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.09), ncol=2, fontsize=8.5, frameon=False)
    for s in ("top", "right"):
        ax.spines[s].set_visible(False)
    ax.set_title("Forest above field: C-band VH +{:.1f} dB,\nL-band HV +{:.1f} dB".format(contrast["C_VH"], contrast["L_HV"]), loc="left", fontsize=10.5)
    fig.suptitle("Berlin in two wavelengths: forest and grass separate far more at L-band",
                 fontsize=12, fontweight="bold", color=INK, x=0.01, ha="left")
    credit(fig, S1_CREDIT + "  " + PALSAR_CREDIT)
    fig.subplots_adjust(left=0.02, right=0.98, top=0.88, bottom=0.16)
    fig.savefig(OUT / "12_wavelength.png"); plt.close(fig)


# ------------------------------------------------------------- 13. brightness and units
def fig_brightness(it):
    vv = s1_db(it, "vv", BB)
    href = it.assets["vv"].href
    px = {k: lonlat_to_px(href, BB, *v) for k, v in MARKS.items()}
    med = {k: round(float(np.nanmedian(vv[int(r) - 15:int(r) + 15, int(c) - 15:int(c) + 15])), 1) for k, (c, r) in px.items()}
    vals = vv[np.isfinite(vv)]
    p = {f"p{q}": round(float(np.percentile(vals, q)), 1) for q in (1, 50, 99)}
    FACTS["brightness"] = {"s1_date": it.properties["datetime"][:10], "box_medians_vv_db": med, "image_percentiles_vv_db": p,
                           "forest_over_field_power_ratio": round(10 ** ((med["forest"] - med["field"]) / 10), 1),
                           "city_over_lake_power_ratio": round(10 ** ((med["city"] - med["lake"]) / 10), 1)}
    fig, axs = plt.subplots(1, 2, figsize=(13, 4.4), gridspec_kw={"width_ratios": [1.6, 1]})
    ax = axs[0]
    ax.hist(vals, bins=np.arange(-30, 12, 0.5), color="#9aa5b1")
    cols = {"lake": "#1f4e79", "field": "#7a8b3a", "forest": "#2f7d32", "city": "#c2410c"}
    ymax = ax.get_ylim()[1]
    for k in ("lake", "field", "forest", "city"):
        ax.axvline(med[k], color=cols[k], lw=2)
        ax.text(med[k] + 0.3, ymax * (0.97 - 0.13 * list(cols).index(k)), f"{NAMES[k]}\n{med[k]} dB", color=cols[k], fontsize=8.5, fontweight="bold", va="top",
                bbox=dict(boxstyle="round,pad=0.15", fc="white", ec="none", alpha=0.85))
    ax.set_xlabel("Sentinel-1 VV backscatter, gamma0 terrain-flattened (dB)"); ax.set_ylabel("pixels")
    ax.set_yticks([])
    for s in ("top", "right", "left"):
        ax.spines[s].set_visible(False)
    ax.set_title(f"Every pixel of the Berlin image, {it.properties['datetime'][:10]}, with the four sample medians", loc="left")
    ax = axs[1]
    db = np.array([-20, -10, -6, -3, 0, 3, 6, 10])
    ax.scatter(db, 10 ** (db / 10), color=ACC, zorder=3)
    for d in (-10, -3, 3, 10):
        ax.annotate(f"{d:+d} dB = ×{10 ** (d / 10):.2g}", (d, 10 ** (d / 10)), xytext=(8, 6), textcoords="offset points", fontsize=9, color=INK)
    ax.set_yscale("log"); ax.set_xlabel("decibels"); ax.set_ylabel("power ratio (log scale)")
    for s in ("top", "right"):
        ax.spines[s].set_visible(False)
    ax.set_title("Decibels are ratios: +3 dB doubles, +10 dB is ten times", loc="left")
    credit(fig, S1_CREDIT)
    fig.tight_layout(rect=(0, 0.03, 1, 1))
    fig.savefig(OUT / "13_brightness.png"); plt.close(fig)


# ------------------------------------------------------------- 14. dual-pol colour composite
def fig_dualpol(it):
    vv, vh = s1_db(it, "vv", BB), s1_db(it, "vh", BB)
    rng = {"R": (-20.0, 2.0), "G": (-27.0, -7.0), "B": (2.0, 12.0)}
    rgb = np.dstack([to_byte(vv, *rng["R"]), to_byte(vh, *rng["G"]), to_byte(vv - vh, *rng["B"])])
    FACTS["dualpol"] = {"date": it.properties["datetime"][:10], "R": "VV dB -20..2", "G": "VH dB -27..-7", "B": "VV-VH (dB ratio) 2..12"}
    fig, ax = plt.subplots(figsize=(13, 5.0))
    ax.imshow(rgb)
    href = it.assets["vv"].href
    for k, (lon, lat) in MARKS.items():
        c, r = lonlat_to_px(href, BB, lon, lat)
        ax.add_patch(plt.Rectangle((c - 15, r - 15), 30, 30, fill=False, color="white", lw=1.4))
        ax.text(c + 20, r - 18, NAMES[k], color="white", fontsize=9, fontweight="bold",
                bbox=dict(boxstyle="round,pad=0.2", fc="#000000b0", ec="none"))
    clean(ax); scalebar(ax, 10, 5000, "5 km")
    ax.set_title(f"Berlin, Sentinel-1 {it.properties['datetime'][:10]}: red = VV, green = VH, blue = VV/VH ratio", loc="left")
    credit(fig, S1_CREDIT)
    fig.tight_layout(rect=(0, 0.02, 1, 1))
    fig.savefig(OUT / "14_dualpol.png"); plt.close(fig)


# ------------------------------------------------------------- 15. coherence
COH = "https://sentinel-1-global-coherence-earthbigdata.s3.us-west-2.amazonaws.com/data/tiles/N53E013/N53E013_{}.tif"


def coh(name):
    a = read_geo(COH.format(name), BB, cache_key=f"coh_N53E013_{name}.npy").copy()
    a[a <= 0] = np.nan
    return a / 100.0  # stored as coherence x 100 (uint8)


def fig_coherence():
    w12, s12 = coh("winter_vv_COH12"), coh("summer_vv_COH12")
    w48 = coh("winter_vv_COH48")
    w06 = coh("winter_vv_COH06")
    med = {}
    for nm, arr in (("winter_12d", w12), ("summer_12d", s12), ("winter_6d", w06), ("winter_48d", w48)):
        med[nm] = {k: round(box_median(arr, BB, *v), 2) for k, v in MARKS.items()}
    FACTS["coherence"] = {"dataset": "Global Seasonal Sentinel-1 Interferometric Coherence and Backscatter Data Set, tile N53E013",
                          "period": "1 Dec 2019 - 30 Nov 2020", "winter": "Dec-Feb", "summer": "Jun-Aug",
                          "pixel_spacing": "3 arcsec (about 90 m N-S)", "box_medians": med}
    fig, axs = plt.subplots(1, 2, figsize=(13, 3.9))
    for ax, arr, ttl in ((axs[0], w12, "Winter (Dec-Feb), 12-day pairs"), (axs[1], s12, "Summer (Jun-Aug), 12-day pairs")):
        im = ax.imshow(arr, cmap="magma", vmin=0, vmax=0.8, aspect=1 / np.cos(np.radians(52.49)))
        for k in ("forest", "field", "city", "lake"):
            lon, lat = MARKS[k]
            c = (lon - BB[0]) / (BB[2] - BB[0]) * arr.shape[1]; r = (BB[3] - lat) / (BB[3] - BB[1]) * arr.shape[0]
            ax.add_patch(plt.Rectangle((c - 3, r - 2), 6, 4, fill=False, color="#7fe0ff", lw=1.4))
        clean(ax); ax.set_title(ttl, loc="left")
    cax = fig.add_axes([0.915, 0.1, 0.012, 0.7]); cb = fig.colorbar(im, cax=cax); cb.set_label("coherence (0 = nothing in common, 1 = identical)", fontsize=8.5)
    fig.suptitle("Berlin, Sentinel-1 VV coherence: the city keeps its echo between passes, forest and water do not",
                 fontsize=12, fontweight="bold", color=INK, x=0.01, ha="left")
    credit(fig, COH_CREDIT)
    fig.subplots_adjust(left=0.01, right=0.9, top=0.86, bottom=0.06, wspace=0.03)
    fig.savefig(OUT / "15_coherence.png"); plt.close(fig)


# ------------------------------------------------------------- 16. phase (schematic + simulation)
def fig_phase():
    lam = C_LIGHT / 5.405e9
    fig, axs = plt.subplots(1, 3, figsize=(13, 4.3), gridspec_kw={"width_ratios": [1.15, 1, 1]})
    ax = axs[0]
    ax.plot([0, 10], [0, 0], color="#6d5d3f", lw=2)
    ax.fill_between([0, 10], -1, 0, color="#e9e1cf")
    ax.fill_between([3.5, 6.5], -1, -0.0, color="#d8c9a6")
    xs = np.linspace(3.5, 6.5, 50)
    ax.plot(xs, -0.55 * np.exp(-((xs - 5) / 0.8) ** 2), color="#c2410c", lw=2)
    ax.plot([1, 5], [6, 0], color=ACC, lw=1.3); ax.plot([1, 5], [6, -0.55], color="#c2410c", lw=1.3, ls="--")
    ax.plot(1, 6, marker="s", ms=11, color=INK)
    ax.text(1.3, 6.1, "same orbit track,\ntwo dates", fontsize=9, va="bottom")
    ax.text(5.3, -0.75, "ground sank", color="#c2410c", fontsize=9, va="top")
    ax.text(5.6, 3.2, "path longer by ΔR\non the second date", fontsize=9, color="#c2410c")
    ax.set_xlim(0, 10); ax.set_ylim(-1.2, 7.4); clean(ax)
    ax.set_title("A. Change in distance → change in phase", loc="left", fontsize=10.5)
    n = 300
    yy, xx = np.mgrid[0:n, 0:n] / n
    defo = -0.06 * np.exp(-(((xx - 0.5) ** 2 + (yy - 0.5) ** 2) / (2 * 0.13 ** 2)))  # 6 cm subsidence bowl
    phase = np.angle(np.exp(1j * (4 * np.pi * (-defo) / lam)))
    rng = np.random.default_rng(1)
    noisy = phase.copy()
    mask = (xx > 0.68) & (yy < 0.42)
    noisy[mask] = rng.uniform(-np.pi, np.pi, mask.sum())
    axs[1].imshow(phase, cmap="twilight", vmin=-np.pi, vmax=np.pi); clean(axs[1])
    axs[1].set_title(f"B. Simulated: 6 cm of line-of-sight change,\nC-band (one colour cycle = {lam / 2 * 100:.1f} cm)", loc="left", fontsize=10.5)
    axs[2].imshow(noisy, cmap="twilight", vmin=-np.pi, vmax=np.pi); clean(axs[2])
    axs[2].text(0.84, 0.2, "low coherence:\nphase is noise", transform=axs[2].transAxes, ha="center", fontsize=9, color="white",
                bbox=dict(boxstyle="round,pad=0.25", fc="#000000a0", ec="none"))
    axs[2].set_title("C. Simulated: the same bowl where\npart of the scene lost coherence", loc="left", fontsize=10.5)
    fig.suptitle("Interferometry: the phase difference between two passes measures change in distance (A schematic; B and C simulated)",
                 fontsize=12, fontweight="bold", color=INK, x=0.01, ha="left")
    FACTS["phase"] = {"c_band_wavelength_cm": round(lam * 100, 2), "c_band_cm_per_fringe": round(lam / 2 * 100, 2),
                      "x_band_cm_per_fringe_9_65GHz": round(C_LIGHT / 9.65e9 / 2 * 100, 2),
                      "l_band_cm_per_fringe_1_2575GHz": round(C_LIGHT / 1.2575e9 / 2 * 100, 1), "simulated_bowl_cm": 6,
                      "simulated_fringes": round(6 / (lam / 2 * 100), 1)}
    fig.tight_layout(rect=(0, 0.0, 1, 0.9))
    fig.savefig(OUT / "16_phase.png"); plt.close(fig)


def q_images(it):
    """Unlabelled items for the final assessment: which image is L-band; which letter is the city."""
    from PIL import Image, ImageDraw, ImageFont
    try:
        font = ImageFont.truetype("arialbd.ttf", 30)
    except OSError:
        font = ImageFont.load_default()
    hv, _ = palsar("HV")
    vh = s1_on_grid(it, "vh", hv.shape)
    sub = [13.20, 52.445, 13.45, 52.515]  # Grunewald to Tempelhof
    h, w = hv.shape
    c0, c1 = int((sub[0] - BB[0]) / (BB[2] - BB[0]) * w), int((sub[2] - BB[0]) / (BB[2] - BB[0]) * w)
    r0, r1 = int((BB[3] - sub[3]) / (BB[3] - BB[1]) * h), int((BB[3] - sub[1]) / (BB[3] - BB[1]) * h)
    tiles = []
    for arr in (hv, vh):  # image 1 = L-band HV, image 2 = C-band VH (opposite order to fig 12)
        t = Image.fromarray(to_byte(arr[r0:r1, c0:c1], -28, -6))
        sx = 1 / np.cos(np.radians(52.48))
        t = t.resize((int(t.width * 1.6), int(t.height * 1.6 * sx)), Image.LANCZOS).convert("RGB")
        tiles.append(t)
    out = Image.new("RGB", (tiles[0].width, tiles[0].height * 2 + 60 + 16), "white")
    d = ImageDraw.Draw(out)
    for k, t in enumerate(tiles):
        y = k * (t.height + 46) + 38
        out.paste(t, (0, y))
        d.text((4, y - 36), f"Image {k + 1}", fill=(0, 0, 0), font=font)
    out.save(OUT / "q_bands.png", optimize=True)
    FACTS["q_bands"] = {"image_1": "L-band HV (PALSAR-2 2021)", "image_2": "C-band VH (Sentinel-1)", "bbox": sub}
    # coherence letters
    w12 = coh("winter_vv_COH12")
    img = Image.fromarray((plt.get_cmap("magma")(np.nan_to_num(np.clip(w12 / 0.8, 0, 1)))[..., :3] * 255).astype("uint8"))
    sx = 1 / np.cos(np.radians(52.49))
    S = 2
    img = img.resize((img.width * S, int(img.height * S * sx)), Image.NEAREST)
    d = ImageDraw.Draw(img)
    letters = {"A": "forest", "B": "lake", "C": "field", "D": "city"}
    for L, k in letters.items():
        lon, lat = MARKS[k]
        x = (lon - BB[0]) / (BB[2] - BB[0]) * img.width
        y = (BB[3] - lat) / (BB[3] - BB[1]) * img.height
        d.ellipse([x - 13, y - 13, x + 13, y + 13], outline=(127, 224, 255), width=4)
        d.rounded_rectangle([x + 16, y - 46, x + 50, y - 8], 6, fill=(0, 0, 0))
        d.text((x + 22, y - 44), L, fill=(127, 224, 255), font=font)
    img.save(OUT / "q_coherence.png", optimize=True)
    FACTS["q_coherence"] = {"letters": letters, "layer": "winter_vv_COH12", "values": FACTS["coherence"]["box_medians"]["winter_12d"]}


def main():
    it = s1_item()
    fig_formation()
    fig_wavelength(it)
    fig_brightness(it)
    fig_dualpol(it)
    fig_coherence()
    fig_phase()
    q_images(it)
    (HERE / "course_facts.json").write_text(json.dumps(FACTS, indent=1, ensure_ascii=False), encoding="utf-8")
    print(json.dumps(FACTS, indent=1, ensure_ascii=False))


if __name__ == "__main__":
    main()
