"""Unseen-place image items for the final assessment (places and dates the lessons never show).

  q_tiles2.png     Leipzig, Sentinel-1 VV: four 750 m tiles chosen by ESA WorldCover 2021 class purity
  q_coh2.png       Leipzig, global coherence (winter, 12-day), four lettered places chosen the same way
  q_alps.png       Bernese Oberland, one terrain-corrected Sentinel-1 pass, no metadata: which side was the radar?
  q_port.png       Bremerhaven container terminal, same-track change composite, lettered

Every answer comes from data, never from eyeballing: WorldCover classes for the tiles and coherence
letters; the STAC orbit direction plus a slope-aspect brightness test for the Alps; the water mask and
per-date brightness for the port letters. Numbers go to unseen_facts.json.

Run:  ../../../../.venv_sar/Scripts/python build_unseen.py
"""
import json
import pathlib
import sys

import numpy as np
import rasterio
from PIL import Image, ImageDraw, ImageFont
from rasterio.enums import Resampling
from rasterio.warp import reproject
from scipy import ndimage as ndi

sys.path.insert(0, str(pathlib.Path(__file__).parent))
from sarlib import CACHE, read_window, s1_db, search, to_byte

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "img"
FACTS = {}
RING = (255, 216, 0)
try:
    FONT = ImageFont.truetype("arialbd.ttf", 30)
    SMALL = ImageFont.truetype("arial.ttf", 16)
except OSError:
    FONT = SMALL = ImageFont.load_default()
S1_CREDIT = "Contains modified Copernicus Sentinel data (2026)."
END = "2026-11-21"  # pinned, like every other figure


def label(d, x, y, t, dx=24, dy=-56, r=16):
    d.ellipse([x - r, y - r, x + r, y + r], outline=RING, width=4)
    tx, ty = x + dx, y + dy
    d.rounded_rectangle([tx - 4, ty - 4, tx + 30, ty + 34], 6, fill=(0, 0, 0))
    d.text((tx + 3, ty), t, fill=RING, font=FONT)


def credit_strip(im, text):
    lines, cur = [], ""
    for w in text.split(" "):
        trial = (cur + " " + w).strip()
        if SMALL.getlength(trial) > im.width - 12 and cur:
            lines.append(cur); cur = w
        else:
            cur = trial
    lines.append(cur)
    framed = Image.new("RGB", (im.width, im.height + 21 * len(lines) + 8), "white")
    framed.paste(im, (0, 0))
    d = ImageDraw.Draw(framed)
    for k, ln in enumerate(lines):
        d.text((im.width - 6, im.height + 5 + 21 * k), ln, fill=(90, 100, 112), font=SMALL, anchor="ra")
    return framed


def on_grid(href, tr, crs, shape, nearest=True, key=None):
    """Reproject any raster onto an existing grid."""
    if key and (CACHE / key).exists():
        return np.load(CACHE / key)
    dst = np.zeros(shape, "float32")
    with rasterio.open(href) as src:
        reproject(rasterio.band(src, 1), dst, dst_transform=tr, dst_crs=crs,
                  resampling=Resampling.nearest if nearest else Resampling.bilinear)
    if key:
        np.save(CACHE / key, dst)
    return dst


def grid_of(item, bb):
    _, tr, crs = read_window(item.assets["vv"].href, bb)
    return tr, crs


def worldcover(bb, tr, crs, shape, key):
    it = [i for i in search("esa-worldcover", bb, "2021-01-01/2021-12-31")][0]
    return on_grid(it.assets["map"].href, tr, crs, shape, key=key), it.id


def purest(cls, want, T, avoid=(), near=None, radius=None):
    """Top-left (r, c) of the T x T tile with the highest share of class `want` (any of a tuple).
    near/radius (pixels) restrict the search, e.g. built-up to the old town rather than a suburb."""
    m = np.isin(cls, want).astype("float32")
    share = ndi.uniform_filter(m, T, mode="constant")
    if near is not None:
        rr, cc = np.indices(share.shape)
        share[np.hypot(rr - near[0], cc - near[1]) > radius] = 0
    for r0, c0 in avoid:  # keep tiles apart
        share[max(0, r0 - T):r0 + 2 * T, max(0, c0 - T):c0 + 2 * T] = 0
    e = max(T // 2 + 1, 120)  # keep away from the edges, so a label fits and the tile is not cut
    share[:e, :] = 0; share[-e:, :] = 0; share[:, :e] = 0; share[:, -e:] = 0
    r, c = np.unravel_index(np.argmax(share), share.shape)
    return int(r - T // 2), int(c - T // 2), round(float(share[r, c]), 3)


# ------------------------------------------------------------------ Leipzig
LEI = [12.20, 51.22, 12.55, 51.42]
CENTRE = (12.3747, 51.3397)  # Leipzig old town (Markt)


def leipzig():
    items = [i for i in search("sentinel-1-rtc", LEI, f"2026-11-01/{END}") if i.properties["sat:orbit_state"] == "descending"]
    it = items[-1]
    vv = s1_db(it, "vv", LEI)
    tr, crs = grid_of(it, LEI)
    cls, wc_id = worldcover(LEI, tr, crs, vv.shape, "wc_leipzig.npy")
    T = 75  # 750 m at 10 m
    from sarlib import lonlat_to_px
    cc, rr = lonlat_to_px(it.assets["vv"].href, LEI, *CENTRE)
    picks, avoid = {}, []
    for name, want in (("water", (80,)), ("forest", (10,)), ("city", (50,)), ("field", (30, 40))):
        kw = {"near": (rr, cc), "radius": 150} if name == "city" else {}
        r, c, sh = purest(cls, want, T, avoid, **kw)
        avoid.append((r, c))
        tile = vv[r:r + T, c:c + T]
        picks[name] = {"r": r, "c": c, "share": sh, "median_db": round(float(np.nanmedian(tile)), 1)}
    # tile order on the page: A..D; the forest must not be in an obvious slot
    order = ["field", "city", "water", "forest"]
    S = 3
    out = Image.new("RGB", (4 * T * S + 3 * 24, T * S + 50), "white")
    d = ImageDraw.Draw(out)
    for k, name in enumerate(order):
        p = picks[name]
        t = Image.fromarray(to_byte(vv[p["r"]:p["r"] + T, p["c"]:p["c"] + T], -25, 5)).resize((T * S, T * S), Image.NEAREST).convert("RGB")
        out.paste(t, (k * (T * S + 24), 50))
        d.text((k * (T * S + 24) + 4, 6), "ABCD"[k], fill=(0, 0, 0), font=FONT)
    out = credit_strip(out, S1_CREDIT + " Tiles chosen by land cover. Land cover: © ESA WorldCover project 2021 / Contains modified Copernicus Sentinel data (2021) processed by ESA WorldCover consortium, CC BY 4.0.")
    out.save(OUT / "q_tiles2.png", optimize=True)
    FACTS["q_tiles2"] = {"place": "Leipzig", "s1": it.id, "date": it.properties["datetime"][:10], "worldcover": wc_id,
                         "letters": dict(zip("ABCD", order)), "tiles": picks, "stretch_db": [-25, 5]}

    # coherence over Leipzig: tile N52E012, winter 12-day
    href = "https://sentinel-1-global-coherence-earthbigdata.s3.us-west-2.amazonaws.com/data/tiles/N52E012/N52E012_winter_vv_COH12.tif"
    coh = on_grid(href, tr, crs, vv.shape, nearest=False, key="coh_leipzig_w12.npy") / 100.0
    coh[coh <= 0] = np.nan
    Tc = 50  # 500 m sample windows, so a ring cannot sit on an edge
    cp, avoid = {}, []
    for name, want in (("water", (80,)), ("forest", (10,)), ("city", (50,)), ("field", (30, 40))):
        kw = {"near": (rr, cc), "radius": 150} if name == "city" else {}
        r, c, sh = purest(cls, want, Tc, avoid, **kw)
        avoid.append((r, c))
        cp[name] = {"r": r + Tc // 2, "c": c + Tc // 2, "share": sh,
                    "median_coh": round(float(np.nanmedian(coh[r:r + Tc, c:c + Tc])), 2),
                    "ring_coh_100m": round(float(np.nanmedian(coh[r + Tc // 2 - 5:r + Tc // 2 + 5, c + Tc // 2 - 5:c + Tc // 2 + 5])), 2)}
    import matplotlib.pyplot as plt
    rgb = (plt.get_cmap("magma")(np.nan_to_num(np.clip(coh / 0.8, 0, 1)))[..., :3] * 255).astype("uint8")
    im = Image.fromarray(rgb)
    f = 0.5  # 20 m display pixels
    im = im.resize((int(im.width * f), int(im.height * f)), Image.LANCZOS)
    d = ImageDraw.Draw(im)
    corder = {"A": "city", "B": "field", "C": "forest", "D": "water"}
    for L, name in corder.items():
        label(d, cp[name]["c"] * f, cp[name]["r"] * f, L)
    im = credit_strip(im, "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). Places chosen by land cover. Land cover: © ESA WorldCover project 2021 / Contains modified Copernicus Sentinel data (2021) processed by ESA WorldCover consortium, CC BY 4.0.")
    im.save(OUT / "q_coh2.png", optimize=True)
    FACTS["q_coh2"] = {"place": "Leipzig", "layer": "N52E012 winter_vv_COH12", "letters": corder, "samples": cp}
    np.save(CACHE / "lei_preview.npy", vv)


# ------------------------------------------------------------------ Alps
ALP = [8.00, 46.54, 8.14, 46.63]   # Bernese Oberland: Eiger, Grindelwald valley (inside one DEM tile)


def alps():
    items = search("sentinel-1-rtc", ALP, f"2026-10-15/{END}")
    asc = [i for i in items if i.properties["sat:orbit_state"] == "ascending"][-1]
    vv = s1_db(asc, "vv", ALP)
    tr, crs = grid_of(asc, ALP)
    dem_it = search("cop-dem-glo-30", ALP, None)[0]
    dem = on_grid(dem_it.assets["data"].href, tr, crs, vv.shape, nearest=False, key="dem_alps.npy")
    gy, gx = np.gradient(dem, 10.0)          # rows run south, so -gy is the northward gradient
    slope = np.degrees(np.arctan(np.hypot(gx, gy)))
    steep = slope > 25
    east_facing = steep & (gx < 0) & (np.abs(gx) > np.abs(gy))   # ground falls towards the east
    west_facing = steep & (gx > 0) & (np.abs(gx) > np.abs(gy))
    lin = 10 ** (vv / 10)
    e_db = 10 * np.log10(np.nanmean(lin[east_facing])); w_db = 10 * np.log10(np.nanmean(lin[west_facing]))
    dark = vv < -20
    FACTS["q_alps"] = {"s1": asc.id, "date": asc.properties["datetime"][:10], "orbit": asc.properties["sat:orbit_state"],
                       "relative_orbit": asc.properties["sat:relative_orbit"], "radar_looks": "east (Sentinel-1 is right-looking)",
                       "mean_db_east_facing_steep": round(e_db, 1), "mean_db_west_facing_steep": round(w_db, 1),
                       "dark_lt_-20_pct_east_facing": round(float(dark[east_facing].mean()) * 100, 1),
                       "dark_lt_-20_pct_west_facing": round(float(dark[west_facing].mean()) * 100, 1),
                       "elev_range_m": [int(np.nanmin(dem[dem > 0])), int(np.nanmax(dem))], "dem": dem_it.id}
    assert FACTS["q_alps"]["mean_db_west_facing_steep"] > FACTS["q_alps"]["mean_db_east_facing_steep"] + 3, "slope test does not support the answer"
    # two matched markers, placed from the data: the strongest patch of shadow on steep east-facing slopes, and
    # the strongest patch of bright return on steep west-facing slopes (25 px = 250 m windows, away from the edges)
    def peak(mask, avoid=None):
        sc = ndi.uniform_filter(mask.astype("float32"), 25)
        sc[:60, :] = 0; sc[-60:, :] = 0; sc[:, :70] = 0; sc[:, -60:] = 0
        if avoid is not None:
            rr, cc = np.indices(sc.shape); sc[np.hypot(rr - avoid[0], cc - avoid[1]) < 150] = 0
        r, c = np.unravel_index(np.argmax(sc), sc.shape)
        return int(r), int(c), round(float(sc[r, c]), 2)
    m1 = peak(east_facing & (vv < -20))
    m2 = peak(west_facing & (vv > 0), avoid=m1[:2])
    FACTS["q_alps"]["markers"] = {"1_shadow_on_east_facing": m1, "2_bright_on_west_facing": m2,
                                  "note": "row, col, share of the 250 m window meeting the test"}
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    demv = np.where(dem > 0, dem, np.nan)
    fig, axs = plt.subplots(1, 2, figsize=(13, 5.9))
    axs[0].imshow(to_byte(vv[:, 4:], -25, 5), cmap="gray"); axs[0].set_title("Radar, one pass, terrain-corrected", loc="left", fontsize=11, fontweight="bold")
    im1 = axs[1].imshow(demv[:, 4:], cmap="terrain", vmin=500, vmax=4300)
    axs[1].contour(demv[:, 4:], levels=np.arange(750, 4250, 250), colors="k", linewidths=0.35, alpha=0.55)
    axs[1].set_title("The same area: elevation, 250 m contours", loc="left", fontsize=11, fontweight="bold")
    cb = fig.colorbar(im1, ax=axs[1], fraction=0.035, pad=0.02); cb.set_label("metres", fontsize=9)
    for ax in axs:
        for k, (r, c, _) in (("1", m1), ("2", m2)):
            ax.plot(c - 4, r, marker="o", ms=26, mfc="none", mec="#ff50c8", mew=2.5)
            ax.text(c - 4 + 22, r - 22, k, color="#ff50c8", fontsize=13, fontweight="bold",
                    bbox=dict(boxstyle="round,pad=0.15", fc="#000000cc", ec="none"))
        ax.set_xticks([]); ax.set_yticks([])
        ax.annotate("N", xy=(0.95, 0.95), xytext=(0.95, 0.83), xycoords="axes fraction", ha="center", va="center",
                    fontsize=12, fontweight="bold", color="white", arrowprops=dict(arrowstyle="-|>", color="white", lw=2.5),
                    bbox=dict(boxstyle="round,pad=0.2", fc="#000000aa", ec="none"))
        w = ax.get_xlim()[1] - ax.get_xlim()[0]
        ax.plot([0.04, 0.04 + 200 / w], [0.05, 0.05], transform=ax.transAxes, color="white", lw=3)
        ax.text(0.04 + 100 / w, 0.08, "2 km", transform=ax.transAxes, color="white", ha="center", fontsize=8, fontweight="bold",
                bbox=dict(boxstyle="round,pad=0.2", fc="#000000aa", ec="none"))
    fig.text(0.995, 0.005, "Contains modified Copernicus Sentinel data (2026), via Microsoft Planetary Computer. Elevation: produced using Copernicus WorldDEM-30 "
             "(c) DLR e.V. 2010-2014 and (c) Airbus Defence and Space GmbH 2014-2018\nprovided under COPERNICUS by the European Union and ESA; all rights reserved.",
             ha="right", va="bottom", fontsize=6.5, color="#6b7785")
    fig.tight_layout(rect=(0, 0.04, 1, 1))
    fig.savefig(OUT / "q_alps.png", dpi=120); plt.close(fig)


# ------------------------------------------------------------------ Bremerhaven
BRE = [8.47, 53.55, 8.60, 53.62]


def port():
    items = search("sentinel-1-rtc", BRE, f"2026-09-15/{END}")
    orbs = {}  # orbit -> date -> frames (a pass can be split over two adjacent frames)
    for i in items:
        orbs.setdefault(i.properties["sat:relative_orbit"], {}).setdefault(i.properties["datetime"][:10], []).append(i)
    orb = max(orbs, key=lambda o: (len(orbs[o]), max(orbs[o])))
    dates = sorted(orbs[orb])
    its = [orbs[orb][dd][0] for dd in dates]
    stack = np.stack([np.nanmax(np.stack([s1_db(f, "vv", BRE) for f in orbs[orb][dd]]), axis=0) for dd in dates])
    lo = np.nanpercentile(stack, 20, axis=0)
    w = ndi.binary_fill_holes(ndi.binary_opening(lo < -13, iterations=2))
    lab, n = ndi.label(w)
    sz = ndi.sum(w, lab, range(1, n + 1))
    water = np.isin(lab, 1 + np.where(sz > 3000)[0])
    inner = ndi.binary_erosion(water, iterations=3)
    land = ~ndi.binary_dilation(water, iterations=4)
    a, b = stack[-2], stack[-1]
    np.save(CACHE / "bre_pair.npy", np.stack([a, b, inner.astype("float32"), land.astype("float32")]))
    dist_water = ndi.distance_transform_edt(~water)  # pixels (10 m) from the nearest water

    up = ndi.uniform_filter(np.nan_to_num(b - a), 5)  # local change, 50 m window

    def biggest(mask, mn, score):
        """Largest blob; the ring goes on its strongest 50 m patch of change, not its centroid."""
        lab, n = ndi.label(ndi.binary_dilation(mask, iterations=1))
        sz = ndi.sum(mask, lab, range(1, n + 1))
        k = int(np.argmax(sz))
        if sz[k] < mn:
            raise SystemExit(f"no blob >= {mn} px")
        s = np.where((lab == k + 1) & mask, score, -np.inf)
        r, c = np.unravel_index(np.argmax(s), s.shape)
        return int(c), int(r), int(sz[k])

    arrived = biggest((b > 3) & (a < -8) & inner & (np.arange(a.shape[0])[:, None] > 500), 40, up)   # in the inner harbour
    left = biggest((a > 3) & (b < -8) & inner, 40, -up)
    yard = biggest((b - a > 8) & (b > 0) & (dist_water > 15), 40, up)                                 # >150 m inland
    # open water away from targets: whole-area brightening between the dates (wind)
    open_w = inner & (dist_water == 0)
    rr, cc = np.indices(a.shape)
    zone = open_w & (cc < 230) & (rr > 200) & (rr < 420)
    lin = lambda x: 10 * np.log10(np.nanmean(10 ** (x / 10)))
    haze = {"x_y": [110, 300], "mean_db_first": round(lin(a[zone]), 1), "mean_db_second": round(lin(b[zone]), 1), "n_px": int(zone.sum())}
    assert zone[300, 110], "haze letter is not on open water"
    pts = {"A": arrived, "B": haze["x_y"], "C": left, "D": yard}
    for L, p in pts.items():
        print(L, p, "a=%.1f b=%.1f water=%s dist=%.0f" % (a[p[1], p[0]], b[p[1], p[0]], bool(water[p[1], p[0]]), dist_water[p[1], p[0]]))
    x0, y0, x1, y1 = 0, 60, 760, 740
    S = 1.25
    im = Image.fromarray(np.dstack([to_byte(a, -20, 5), to_byte(b, -20, 5), to_byte(b, -20, 5)])[y0:y1, x0:x1])
    im = im.resize((int(im.width * S), int(im.height * S)), Image.LANCZOS)
    d = ImageDraw.Draw(im)
    offs = {"A": (24, 10), "B": (24, -56), "C": (-60, -56), "D": (24, -56)}
    for L, p in pts.items():
        label(d, (p[0] - x0) * S, (p[1] - y0) * S, L, *offs[L])
    d.rectangle([20, im.height - 30, 20 + 100 * S, im.height - 22], fill="white", outline="black")
    d.text((20 + 50 * S, im.height - 36), "1 km", fill="white", font=SMALL, anchor="mb", stroke_width=2, stroke_fill="black")
    im = credit_strip(im, S1_CREDIT)
    im.save(OUT / "q_port.png", optimize=True)
    FACTS["q_port"] = {"place": "Bremerhaven", "relative_orbit": orb, "orbit": its[-1].properties["sat:orbit_state"],
                       "pair": [its[-2].properties["datetime"][:16], its[-1].properties["datetime"][:16]],
                       "ids": [its[-2].id, its[-1].id], "n_dates": len(its),
                       "letters": {"A": "cyan blob on water in the inner harbour: arrived", "B": "open water, brighter on the second date: wind",
                                   "C": "red on water along the quay: left", "D": "cyan >150 m inland on the terminal: stacks or cranes"},
                       "points_px": pts, "haze": haze, "crop": [x0, y0, x1, y1], "scale": S}


if __name__ == "__main__":
    for f in sys.argv[1:] or ["leipzig", "alps", "port"]:
        globals()[f]()
    (HERE / "unseen_facts.json").write_text(json.dumps(FACTS, indent=1, default=float), encoding="utf-8")
    print(json.dumps(FACTS, indent=1, default=float))
