"""
Builds every figure for the SAR training module from free Sentinel-1 / -2 data
(Microsoft Planetary Computer). Writes PNGs to ../site/img and the measured
numbers used in the text to figures_facts.json, so the page quotes the data,
not memory.

Run:  ../../../../.venv_sar/Scripts/python build_figures.py
"""
import json
import pathlib
import sys

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage as ndi

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

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "img"   # site/img when run from site/code
OUT.mkdir(parents=True, exist_ok=True)
FACTS = {}

plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 10,
                     "axes.titlesize": 11, "axes.titleweight": "bold",
                     "figure.dpi": 110, "savefig.dpi": 150})
INK = "#1d2733"


def scalebar(ax, px_m, length_m, label, loc=(0.04, 0.06), color="white"):
    """Simple scale bar; px_m = metres per pixel of the displayed array."""
    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=color, lw=3,
            solid_capstyle="butt")
    ax.text(x0 + frac / 2, y0 + 0.03, label, transform=ax.transAxes, color=color,
            ha="center", va="bottom", fontsize=8, fontweight="bold",
            bbox=dict(boxstyle="round,pad=0.2", fc="#000000aa", ec="none"))


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


def credit(fig, text="Contains modified Copernicus Sentinel data (2026), via Microsoft Planetary Computer."):
    fig.text(0.995, 0.005, text, ha="right", va="bottom", fontsize=6.5, color="#6b7785")


def date(item):
    return item.properties["datetime"][:10]


# ------------------------------------------------------------------ 1. cloud
def fig_cloud():
    bb = [13.30, 52.48, 13.48, 52.55]
    s2 = search("sentinel-2-l2a", bb, "2026-11-11/2026-11-13")
    cloudy = max([i for i in s2 if i.properties["datetime"].startswith("2026-11-11")],
                 key=lambda i: i.properties["eo:cloud_cover"])
    clear = min([i for i in s2 if i.properties["datetime"].startswith("2026-11-13")],
                key=lambda i: i.properties["eo:cloud_cover"])
    cands = [i for i in search("sentinel-1-rtc", bb, "2026-11-11/2026-11-12")
             if i.properties["datetime"].startswith("2026-11-11")]
    s1 = cands[0]
    # the 11 Nov pass crosses this box on a frame boundary: two consecutive
    # frames of ONE pass each cover part of it; join them pixel by pixel
    frames = [s1_db(i, "vv", bb) for i in cands]
    parts = [x for x in frames if x.shape == frames[0].shape]
    with np.errstate(all="ignore"):
        r_stitched = 10 * np.log10(np.nanmean(np.stack([10 ** (x / 10) for x in parts]), 0))
    # The standard true-colour product ("visual") clips this scene to plain white. Read the raw
    # red/green/blue bands instead (L2A DN - 1000) / 10000 = reflectance) and show 0-0.95
    # reflectance, so the top of the cloud deck keeps its texture.
    refl = []
    for band in ("B04", "B03", "B02"):
        dn, _, _ = read_window(cloudy.assets[band].href, bb)
        refl.append(np.clip((dn - 1000.0) / 10000.0 / 0.95, 0, 1))
    a = (np.dstack(refl) * 255).astype("uint8")
    b = read_rgb(clear.assets["visual"].href, bb)
    r = r_stitched
    fig, axs = plt.subplots(1, 3, figsize=(13, 4.1))
    axs[0].imshow(a); axs[0].set_title(f"Optical, {date(cloudy)}: the top of the cloud")
    axs[1].imshow(to_byte(r, -20, 10), cmap="gray"); axs[1].set_title(f"Radar (Sentinel-1 VV), {date(s1)}, one pass")
    axs[2].imshow(b); axs[2].set_title(f"Optical, {date(clear)}  ({clear.properties['eo:cloud_cover']:.0f}% cloud)")
    for ax in axs:
        clean(ax)
    for s_ in axs[0].spines.values():
        s_.set_visible(True); s_.set_color("#9aa5b1")
    scalebar(axs[1], 10, 2000, "2 km")
    fig.suptitle("Central Berlin: the same day under cloud, optical sees nothing, radar sees the city",
                 fontsize=12, fontweight="bold", color=INK, x=0.01, ha="left")
    credit(fig); fig.tight_layout(rect=(0, 0.02, 1, 0.95))
    fig.savefig(OUT / "01_cloud.png"); plt.close(fig)
    FACTS["cloud"] = {"cloudy_date": date(cloudy), "cloud_pct": round(cloudy.properties["eo:cloud_cover"], 3), "frames": len(parts),
                      "clear_date": date(clear), "clear_pct": round(clear.properties["eo:cloud_cover"]),
                      "radar_date": date(s1), "radar_frames_utc": [i.properties["datetime"][11:16] for i in cands],
                      "optical_time_utc": cloudy.properties["datetime"][11:16]}


# ------------------------------------------------------------- 2. signatures
def fig_signatures():
    bb = [13.15, 52.42, 13.70, 52.56]
    items = [i for i in search("sentinel-1-rtc", bb, "2026-10-01/2026-11-21")
             if i.properties["sat:orbit_state"] == "descending"]
    # one relative orbit only, so every date has the same geometry
    orb = items[-1].properties["sat:relative_orbit"]
    items = [i for i in items if i.properties["sat:relative_orbit"] == orb]
    it = items[-1]
    vv, vh = s1_db(it, "vv", bb), s1_db(it, "vh", bb)
    href = it.assets["vv"].href
    marks = {
        "Müggelsee (lake)": (13.645, 52.438),
        "Grunewald (forest)": (13.225, 52.485),
        "Mitte (dense city)": (13.400, 52.520),
        "Tempelhof field": (13.403, 52.473),
    }
    px = {k: lonlat_to_px(href, bb, *v) for k, v in marks.items()}
    fig, ax = plt.subplots(figsize=(13, 5.0))
    ax.imshow(to_byte(vv, -22, 5), cmap="gray")
    for k, (c, r) in px.items():
        ax.add_patch(plt.Rectangle((c - 15, r - 15), 30, 30, fill=False, color="#ffd84d", lw=1.4))
        ax.annotate(k, (c, r - 16), xytext=(c + 120, r - 160), color="#ffd84d", fontsize=10, fontweight="bold",
                    arrowprops=dict(arrowstyle="->", color="#ffd84d", lw=1.6), bbox=dict(boxstyle="round,pad=0.25", fc="#000000b0", ec="none"))
    clean(ax); scalebar(ax, 10, 5000, "5 km")
    ax.set_title(f"Berlin, Sentinel-1 VV, {date(it)}: dark water, bright city, mid-grey forest, dark-grey open ground "
                 "(boxes = 300 m samples)", loc="left")
    credit(fig); fig.tight_layout(rect=(0, 0.02, 1, 1))
    fig.savefig(OUT / "02_signatures.png"); plt.close(fig)

    # measured backscatter per class (5x5 px boxes are too noisy; use 30x30 px = 300 m)
    def box(arr, c, r, h=15):
        c, r = int(c), int(r)
        return float(np.nanmedian(arr[r - h:r + h, c - h:c + h]))
    FACTS["signatures"] = {"date": date(it), "orbit": f"descending {orb}",
                           "vv_db": {k: round(box(vv, *v), 1) for k, v in px.items()},
                           "vh_db": {k: round(box(vh, *v), 1) for k, v in px.items()}}

    # VV vs VH, and speckle (single date vs multi-date mean), zoomed on Grunewald + Havel edge
    zb = [13.18, 52.45, 13.30, 52.50]
    vvz, vhz = s1_db(it, "vv", zb), s1_db(it, "vh", zb)
    lin = np.stack([10 ** (s1_db(i, "vv", zb) / 10) for i in items])
    mean_db = 10 * np.log10(np.nanmean(lin, 0))
    fig, axs = plt.subplots(1, 3, figsize=(13, 4.3))
    axs[0].imshow(to_byte(vvz, -22, 2), cmap="gray"); axs[0].set_title("VV, one date")
    axs[1].imshow(to_byte(vhz, -28, -6), cmap="gray"); axs[1].set_title("VH, same date")
    axs[2].imshow(to_byte(mean_db, -22, 2), cmap="gray"); axs[2].set_title(f"VV, mean of {len(items)} dates")
    sc, sr = lonlat_to_px(it.assets["vv"].href, zb, 13.225, 52.485)
    for ax in axs:
        clean(ax)
        ax.add_patch(plt.Rectangle((sc - 15, sr - 15), 30, 30, fill=False, color="#ffd84d", lw=1.6))
    scalebar(axs[0], 10, 1000, "1 km")
    fig.suptitle("Grunewald and the Havel: two polarisations, and speckle calmed by averaging dates (box = speckle sample)",
                 fontsize=12, fontweight="bold", color=INK, x=0.01, ha="left")
    credit(fig); fig.tight_layout(rect=(0, 0.02, 1, 0.94))
    fig.savefig(OUT / "03_pol_speckle.png"); plt.close(fig)
    # speckle measured as coefficient of variation over a homogeneous forest patch
    c, r = lonlat_to_px(it.assets["vv"].href, zb, 13.225, 52.485)
    c, r = int(c), int(r)
    one = 10 ** (vvz[r - 15:r + 15, c - 15:c + 15] / 10)
    many = 10 ** (mean_db[r - 15:r + 15, c - 15:c + 15] / 10)
    FACTS["speckle"] = {"n_dates": len(items), "dates": [date(items[0]), date(items[-1])],
                        "orbit": f"descending {orb}", "sample": "300 m box, Grunewald 13.225E 52.485N",
                        "cv_single": round(float(np.nanstd(one) / np.nanmean(one)), 2),
                        "cv_mean": round(float(np.nanstd(many) / np.nanmean(many)), 2)}


# --------------------------------------------------------------- 3. geometry
GEO_BB = [88.30, 27.62, 88.45, 27.74]


def grd_db(item, bbox, shape, crs):
    """Sentinel-1 GRD (NOT terrain corrected), geocoded with its own ground control
    points only, onto the same grid as the RTC window. Uncalibrated DN -> relative dB."""
    import rasterio
    from rasterio.enums import Resampling
    from rasterio.vrt import WarpedVRT
    from rasterio.warp import transform_bounds
    from rasterio.windows import from_bounds
    from sarlib import CACHE
    f = CACHE / f"{item.id}_grd_{'_'.join(f'{v:.3f}' for v in bbox)}.npy"
    if f.exists():
        return np.load(f)
    with rasterio.open(item.assets["vv"].href) as src:
        gcps, gcrs = src.gcps
        with WarpedVRT(src, src_crs=gcrs, crs=crs, resampling=Resampling.bilinear) as vrt:
            b = transform_bounds("EPSG:4326", crs, *bbox, densify_pts=21)
            win = from_bounds(*b, transform=vrt.transform)
            a = vrt.read(1, window=win, out_shape=shape).astype("float32")
    a[a <= 0] = np.nan
    db = 20 * np.log10(a)
    np.save(f, db)
    return db


def fig_geometry():
    bb = GEO_BB
    items = search("sentinel-1-rtc", bb, "2026-11-01/2026-11-21")
    asc = [i for i in items if i.properties["sat:orbit_state"] == "ascending"][-1]
    dsc = [i for i in items if i.properties["sat:orbit_state"] == "descending"][-1]
    a, d = s1_db(asc, "vv", bb), s1_db(dsc, "vv", bb)
    _, _, rtc_crs = read_window(asc.assets["vv"].href, [bb[0], bb[1], bb[0] + 0.001, bb[1] + 0.001])
    # the GRD product of the SAME ascending acquisition, before terrain correction
    grd_items = [i for i in search("sentinel-1-grd", bb, "2026-11-01/2026-11-21")
                 if i.id == asc.id.replace("_rtc", "")]
    assert grd_items, "matching GRD scene not found"
    g = grd_db(grd_items[0], bb, a.shape, rtc_crs)
    g = g - np.nanmedian(g) + np.nanmedian(a)     # relative only: line up the display stretch
    dem_item = search("cop-dem-glo-30", bb, None)[0]
    dem, _, _ = read_window(dem_item.assets["data"].href, bb, out_shape=a.shape)
    gy, gx = np.gradient(dem, 10.0)
    slope = np.arctan(np.hypot(gx, gy))
    aspect = np.arctan2(-gx, gy)
    az, alt = np.radians(270.0), np.radians(45.0)      # lit from the west, where an east-looking radar sits
    hs = np.sin(alt) * np.cos(slope) + np.cos(alt) * np.sin(slope) * np.cos(az - aspect)

    fig, axs = plt.subplots(2, 2, figsize=(12, 10.6))
    axs = axs.ravel()
    axs[0].imshow(hs, cmap="gray"); axs[0].set_title("A. Terrain (Copernicus DEM, shaded from the west)")
    axs[1].imshow(to_byte(g, -25, 5), cmap="gray")
    axs[1].set_title(f"B. Ascending {date(asc)}, not terrain-corrected (GRD)")
    axs[2].imshow(to_byte(a, -25, 5), cmap="gray")
    axs[2].set_title("C. Same pass, terrain-corrected (RTC)")
    axs[3].imshow(to_byte(d, -25, 5), cmap="gray")
    axs[3].set_title(f"D. Descending {date(dsc)}, terrain-corrected (RTC)")
    for ax in axs:
        clean(ax)
    for ax, txt, left in ((axs[1], "radar looks east", False), (axs[2], "radar looks east", False),
                          (axs[3], "radar looks west", True)):
        if left:
            ax.annotate("", xy=(0.06, 0.93), xytext=(0.26, 0.93), xycoords="axes fraction",
                        arrowprops=dict(arrowstyle="-|>", color="#ffd84d", lw=2.5))
            ax.text(0.28, 0.93, txt, transform=ax.transAxes, ha="left", va="center", color="#ffd84d",
                    fontweight="bold", bbox=dict(boxstyle="round,pad=0.2", fc="#000000aa", ec="none"))
        else:
            ax.annotate("", xy=(0.94, 0.93), xytext=(0.74, 0.93), xycoords="axes fraction",
                        arrowprops=dict(arrowstyle="-|>", color="#ffd84d", lw=2.5))
            ax.text(0.72, 0.93, txt, transform=ax.transAxes, ha="right", va="center", color="#ffd84d",
                    fontweight="bold", bbox=dict(boxstyle="round,pad=0.2", fc="#000000aa", ec="none"))
    scalebar(axs[2], 10, 2000, "2 km")
    fig.suptitle("High Himalaya (Sikkim): the same mountains before and after terrain correction, from both sides",
                 fontsize=12, fontweight="bold", color=INK, x=0.01, ha="left")
    credit(fig, "Contains modified Copernicus Sentinel data (2026), via Microsoft Planetary Computer.\nElevation: produced using Copernicus WorldDEM-30 (c) DLR e.V. 2010-2014 and (c) Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.")
    fig.tight_layout(rect=(0, 0.03, 1, 0.96))
    fig.savefig(OUT / "04_geometry.png"); plt.close(fig)
    FACTS["geometry"] = {"asc_date": date(asc), "dsc_date": date(dsc),
                         "asc_orbit": asc.properties["sat:relative_orbit"],
                         "dsc_orbit": dsc.properties["sat:relative_orbit"],
                         "grd_id": grd_items[0].id,
                         "elev_min_m": int(np.nanmin(dem)), "elev_max_m": int(np.nanmax(dem)),
                         "dark_pct_asc": round(float(np.mean(a < -20)) * 100, 1),
                         "dark_pct_dsc": round(float(np.mean(d < -20)) * 100, 1)}


def fig_diagram():
    """Side view of foreshortening, layover and shadow (schematic, not to scale)."""
    fig, axs = plt.subplots(1, 3, figsize=(13, 3.9))
    sat = np.array([-6.0, 9.0])
    cases = [
        ("Foreshortening", [(0, 0), (2.2, 0), (4.2, 1.6), (6.2, 0), (8, 0)],
         "Slope facing the radar: its foot and top are almost the same\ndistance away, so the slope is squeezed into a few bright pixels."),
        ("Layover", [(0, 0), (3.2, 0), (3.9, 3.0), (5.4, 0), (8, 0)],
         "Very steep slope facing the radar: the top is CLOSER than the foot,\nso the peak is drawn in front of its own base."),
        ("Shadow", [(0, 0), (0.2, 0), (3.2, 2.6), (3.7, 0), (8, 0)],
         "Steep slope facing AWAY: the beam passes over it.\nNo echo at all, so the image is black there."),
    ]
    for ax, (name, prof, txt) in zip(axs, cases):
        xs, ys = zip(*prof)
        ax.fill_between(xs, ys, -0.6, color="#c9b48f", zorder=1)
        ax.plot(xs, ys, color="#5a4a2e", lw=2, zorder=2)
        peak = max(prof, key=lambda p: p[1])
        foot_near = prof[1]
        foot_far = prof[3]
        for tgt, col in ((foot_near, "#0b6e99"), (peak, "#d0342c")):
            ax.plot([sat[0], tgt[0]], [sat[1], tgt[1]], color=col, lw=1.4, ls="--", zorder=3)
        if name == "Shadow":
            # grazing ray over the peak, hitting ground behind the back slope
            dx, dy = peak[0] - sat[0], peak[1] - sat[1]
            t = (0 - sat[1]) / dy
            x_hit = sat[0] + dx * t
            ax.plot([peak[0], x_hit], [peak[1], 0], color="#d0342c", lw=1.4, ls=":", zorder=3)
            ax.fill([peak[0], foot_far[0], x_hit], [peak[1], 0, 0], color="#1d2733", alpha=0.35, zorder=2)
            ax.text((peak[0] + x_hit) / 2 + 0.2, 0.25, "shadow", fontsize=9, color="#1d2733", fontweight="bold")
        ax.plot(*sat, marker=(3, 0, 0), ms=13, color="#1d2733")
        ax.text(sat[0] + 0.7, sat[1] + 0.05, "radar", fontsize=9, va="center")
        ax.set_xlim(-6.8, 8.2); ax.set_ylim(-0.6, 9.8); ax.set_aspect("equal")
        ax.set_title(name, fontsize=12, fontweight="bold")
        ax.text(0.5, -0.06, txt, transform=ax.transAxes, ha="center", va="top", fontsize=9, color="#3a4654")
        clean(ax)
    fig.text(0.01, 0.97, "Side view, schematic: blue dashed = beam to the foot of the slope, red = beam to the top",
             fontsize=11, fontweight="bold", color=INK, va="top")
    fig.tight_layout(rect=(0, 0.08, 1, 0.92))
    fig.savefig(OUT / "08_geometry_diagram.png"); plt.close(fig)


# ---------------------------------------------------------------- 4. change
HH = [9.88, 53.52, 10.02, 53.56]


def hamburg():
    items = [i for i in search("sentinel-1-rtc", HH, "2026-10-01/2026-11-21")
             if i.properties["sat:relative_orbit"] == 139]
    stack = np.stack([s1_db(i, "vv", HH) for i in items])
    lo = np.nanpercentile(stack, 20, axis=0)
    w = ndi.binary_fill_holes(ndi.binary_opening(lo < -11, iterations=2))
    lab, n = ndi.label(w)
    sz = ndi.sum(w, lab, range(1, n + 1))
    water = np.isin(lab, 1 + np.where(sz > 2000)[0])
    inner = ndi.binary_erosion(water, iterations=2)
    return items, stack, water, inner


def detect(img, inner, thr=3.0, min_px=4):
    det = (img > thr) & inner
    # one ship often breaks into several bright pieces; dilating 2 px joins pieces up to ~40 m apart
    lab, n = ndi.label(ndi.binary_dilation(det, iterations=2))
    sz = ndi.sum(det, lab, range(1, n + 1))
    cms = ndi.center_of_mass(det, lab, range(1, n + 1))
    return [(c[1], c[0], int(s)) for c, s in zip(cms, sz) if s >= min_px]


def fig_change():
    items, stack, water, inner = hamburg()
    a, b = stack[-2], stack[-1]
    da, db_ = date(items[-2]), date(items[-1])
    rgb = np.dstack([to_byte(a, -20, 5), to_byte(b, -20, 5), to_byte(b, -20, 5)])
    fig, axs = plt.subplots(1, 3, figsize=(13, 3.6), gridspec_kw={"width_ratios": [1, 1, 1]})
    axs[0].imshow(to_byte(a, -20, 5), cmap="gray"); axs[0].set_title(f"{da}")
    axs[1].imshow(to_byte(b, -20, 5), cmap="gray"); axs[1].set_title(f"{db_}")
    axs[2].imshow(rgb); axs[2].set_title("Change: red = gone, cyan = new")
    for ax in axs:
        clean(ax)
    scalebar(axs[0], 10, 2000, "2 km")
    fig.suptitle("Port of Hamburg, same geometry six days apart: red = bright only on the 12th, cyan = only on the 18th",
                 fontsize=12, fontweight="bold", color=INK, x=0.01, ha="left")
    credit(fig); fig.tight_layout(rect=(0, 0.02, 1, 0.92))
    fig.savefig(OUT / "05_change.png"); plt.close(fig)
    counts = [len(detect(stack[k], inner)) for k in range(len(items))]
    FACTS["change"] = {"orbit": "descending 139", "dates": [date(i) for i in items],
                       "pair": [da, db_], "counts_3db": counts,
                       "water_pct": round(float(water.mean()) * 100, 1)}


def fig_exercise():
    items, stack, water, inner = hamburg()
    # exercise crop: Elbe main channel west of the Koehlbrand + Waltershofen side
    r0, r1, c0, c1 = 160, 330, 120, 560
    dates = items[-3:]
    imgs = [stack[len(items) - 3 + k][r0:r1, c0:c1] for k in range(3)]
    inn = inner[r0:r1, c0:c1]
    fig, axs = plt.subplots(3, 1, figsize=(11, 10.2))
    for k, ax in enumerate(axs):
        ax.imshow(to_byte(imgs[k], -20, 5), cmap="gray")
        ax.set_title(f"{chr(65 + k)}: {date(dates[k])}", loc="left")
        clean(ax)
        for gx in range(0, imgs[k].shape[1], 100):
            ax.axvline(gx, color="#ffd84d", lw=1.2, alpha=0.9)
            ax.text(gx + 4, 6, str(gx // 100 + 1), color="#ffd84d", fontsize=13, fontweight="bold", va="top",
                    bbox=dict(boxstyle="round,pad=0.25", fc="#000000b0", ec="none"))
    scalebar(axs[0], 10, 1000, "1 km")
    fig.suptitle("Exercise: which bright targets on the water are there, new, or gone? Columns numbered 1-5.",
                 fontsize=12, fontweight="bold", color=INK, x=0.01, ha="left")
    credit(fig); fig.tight_layout(rect=(0, 0.02, 1, 0.96))
    fig.savefig(OUT / "06_exercise.png"); plt.close(fig)

    # answer key: detections per date, matched across dates within 4 px (40 m)
    dets = [detect(imgs[k], inn) for k in range(3)]

    def col(x):
        return int(x // 100) + 1

    def matched(p, others, tol=4.0):
        return any(np.hypot(p[0] - q[0], p[1] - q[1]) <= tol for q in others)

    key = []
    for k in range(3):
        for p in dets[k]:
            prev = dets[k - 1] if k else None
            nxt = dets[k + 1] if k < 2 else None
            key.append({"image": chr(65 + k), "column": col(p[0]), "x": round(p[0]), "y": round(p[1]),
                        "px": p[2], "in_previous": None if prev is None else matched(p, prev),
                        "in_next": None if nxt is None else matched(p, nxt)})
    fig, axs = plt.subplots(3, 1, figsize=(11, 10.2))
    for k, ax in enumerate(axs):
        ax.imshow(to_byte(imgs[k], -20, 5), cmap="gray")
        ax.set_title(f"{chr(65 + k)}: {date(dates[k])}  -- {len(dets[k])} detections", loc="left")
        clean(ax)
        for x, y, s in dets[k]:
            prev = dets[k - 1] if k else []
            colr = "#ffffff" if k == 0 else ("#29c5ff" if not matched((x, y), prev) else "#ffe14d")
            ax.add_patch(plt.Circle((x, y), 7.5, fill=False, color=colr, lw=3.0))
        if k:
            for x, y, s in dets[k - 1]:
                if not matched((x, y), dets[k]):
                    ax.add_patch(plt.Circle((x, y), 7.5, fill=False, color="#ff3b3b", lw=3.0, ls=(0, (2, 1.5))))
    fig.suptitle("Answer key: white = in A, yellow = still there, blue = new, red dashed = gone",
                 fontsize=12, fontweight="bold", color=INK, x=0.01, ha="left")
    credit(fig); fig.tight_layout(rect=(0, 0.02, 1, 0.96))
    fig.savefig(OUT / "07_answer_key.png"); plt.close(fig)
    FACTS["exercise"] = {"dates": [date(d) for d in dates], "counts": [len(d) for d in dets],
                         "threshold_db": 3.0, "min_px": 4, "match_tol_m": 40, "detections": key,
                         "counts_at_0db": [len(detect(imgs[k], inn, thr=0.0)) for k in range(3)],
                         "counts_at_0db_note": "detect(thr=0.0) on the same three images; quoted in the model confidence statement"}


if __name__ == "__main__":
    for f in (fig_cloud, fig_signatures, fig_geometry, fig_diagram, fig_change, fig_exercise):
        print("building", f.__name__, flush=True)
        f()
    (HERE / "figures_facts.json").write_text(json.dumps(FACTS, indent=1, ensure_ascii=False), encoding="utf-8")
    print(json.dumps({k: v for k, v in FACTS.items() if k != "exercise"}, indent=1, ensure_ascii=False))
    print("exercise counts", FACTS["exercise"]["counts"], FACTS["exercise"]["dates"])
