"""Annotated teaching copies of three figures, so a beginner can find what the text describes.
The unannotated originals stay untouched: the assessment crops are cut from them.

  04_geometry_annot.png  rings 1 and 2 mark the same slopes in C and D (shadow on one pass, smeared on the other);
                         positions checked against the DEM with check_geometry_points.py:
                         C 440,1360 shadow 55% / D 1321,1360 layover 84%;  C 720,1320 shadow 65% / D 1601,1320 layover 100%
                         (found by scanning a 40 px grid for pairs with shadow >= 55% and layover >= 60%)
  05_change_large.png    the Hamburg change composite alone, twice the size, with labels placed from the data
  14_dualpol_annot.png   one label per colour class, each at a point whose colour is asserted below

Run:  ../../../../.venv_sar/Scripts/python annotate_figs.py
"""
import json
import pathlib
import sys

import numpy as np
from PIL import Image, ImageDraw, ImageFont
from scipy import ndimage as ndi

sys.path.insert(0, str(pathlib.Path(__file__).parent))
HERE = pathlib.Path(__file__).resolve().parent
IMG = HERE.parent / "img"
try:
    BOLD = ImageFont.truetype("arialbd.ttf", 22)
    BIG = ImageFont.truetype("arialbd.ttf", 26)
    SMALL = ImageFont.truetype("arial.ttf", 15)
except OSError:
    BOLD = BIG = SMALL = ImageFont.load_default()
FACTS = {}


def tag(d, x, y, text, colour=(255, 255, 255), font=BOLD, anchor="la"):
    """Text on a dark box, readable on any background."""
    l, t, r, b = d.textbbox((x, y), text, font=font, anchor=anchor)
    d.rounded_rectangle([l - 6, t - 4, r + 6, b + 4], 5, fill=(0, 0, 0))
    d.text((x, y), text, fill=colour, font=font, anchor=anchor)


def ring(d, x, y, r, colour, w=4):
    d.ellipse([x - r, y - r, x + r, y + r], outline=(0, 0, 0), width=w + 4)
    d.ellipse([x - r, y - r, x + r, y + r], outline=colour, width=w)


def pointer(d, x0, y0, x1, y1, colour):
    d.line([x0, y0, x1, y1], fill=(0, 0, 0), width=6)
    d.line([x0, y0, x1, y1], fill=colour, width=3)
    d.ellipse([x1 - 5, y1 - 5, x1 + 5, y1 + 5], fill=colour, outline=(0, 0, 0))


# ------------------------------------------------------------- geometry
def geometry():
    im = Image.open(IMG / "04_geometry.png").convert("RGB")
    d = ImageDraw.Draw(im)
    PINK = (255, 80, 200)
    for n, (cx, cy, dx, dy, txt) in {
        "1C": (440, 1360, -34, -14, "1  shadow"), "2C": (720, 1320, -34, -60, "2  shadow"),
        "1D": (1321, 1360, -34, -14, "1  smeared band"), "2D": (1601, 1320, -34, -60, "2  smeared band"),
    }.items():
        ring(d, cx, cy, 26, PINK)
        tag(d, cx + dx, cy + dy, txt, PINK, anchor="ra")
    pointer(d, 1250, 470, 1143, 575, (120, 220, 255))
    tag(d, 1180, 440, "slopes facing the radar: thin bright lines", (120, 220, 255), font=SMALL)
    im.save(IMG / "04_geometry_annot.png", optimize=True)


# ------------------------------------------------------------- change, large
def change():
    import build_figures as bf
    from sarlib import to_byte
    items, stack, water, inner = bf.hamburg()
    a, b = stack[-2], stack[-1]
    dates = [items[-2].properties["datetime"][:10], items[-1].properties["datetime"][:10]]
    up = ndi.uniform_filter(np.nan_to_num(b - a), 5)
    dist = ndi.distance_transform_edt(~water)

    def best(mask, score, mn=8):
        lab, n = ndi.label(ndi.binary_dilation(mask, iterations=1))
        sz = ndi.sum(mask, lab, range(1, n + 1))
        k = int(np.argmax(sz)); assert sz[k] >= mn, mask.sum()
        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])

    pts = {"left": best((a > 3) & (b < -8) & inner, -up), "arrived": best((b > 3) & (a < -8) & inner, up),
           "both": best((a > 3) & (b > 3) & inner, np.minimum(a, b), 4),
           "yard": best((np.abs(b - a) > 8) & (np.maximum(a, b) > 0) & (dist > 15), np.abs(up), 40)}
    S = 2
    rgb = np.dstack([to_byte(a, -20, 5), to_byte(b, -20, 5), to_byte(b, -20, 5)])
    im = Image.fromarray(rgb).resize((rgb.shape[1] * S, rgb.shape[0] * S), Image.LANCZOS)
    top = 46
    canvas = Image.new("RGB", (im.width, im.height + top + 30), "white")
    canvas.paste(im, (0, top))
    d = ImageDraw.Draw(canvas)
    d.text((6, 8), f"Hamburg, change composite: red = bright only on {dates[0]}, cyan = bright only on {dates[1]}, white/grey = bright on both",
           fill=(29, 39, 51), font=BOLD)
    text = {"left": "red on the water: bright only on the 12th (left?)", "arrived": "cyan on the water: bright only on the 18th (arrived?)",
            "both": "white: a small target bright on both dates (fixed structure?)",
            "yard": "change at a terminal: stacks, cranes or a berthed ship? Check a map"}
    for k, (x, y, _) in pts.items():
        X, Y = x * S, y * S + top
        ring(d, X, Y, 26, (255, 216, 0), 3)
        dx, dy, an = {"left": (36, -44, "la"), "arrived": (-36, 30, "ra"), "both": (36, -44, "la"), "yard": (36, 24, "la")}[k]
        tag(d, X + dx, Y + dy, text[k], (255, 216, 0), font=SMALL, anchor=an)
    d.text((canvas.width - 6, canvas.height - 6), "Contains modified Copernicus Sentinel data (2026), via Microsoft Planetary Computer.",
           fill=(107, 119, 133), font=SMALL, anchor="rd")
    canvas.save(IMG / "05_change_large.png", optimize=True)
    FACTS["change_large"] = {"dates": dates, "points_px": pts,
                             "values_db": {k: [round(float(a[y, x]), 1), round(float(b[y, x]), 1)] for k, (x, y, _) in pts.items()}}


# ------------------------------------------------------------- dual-pol
def dualpol():
    im = Image.open(IMG / "14_dualpol.png").convert("RGB")
    px = np.asarray(im).astype(float)

    def colour(x, y):
        return px[y - 5:y + 5, x - 5:x + 5].reshape(-1, 3).mean(0)

    checks = {  # point, label, test on the mean colour
        "tegel": ((590, 70), "dark blue: Tegel airfield, not water", lambda c: c[2] > c[0] + 25 and c[0] < 110),
        "violet": ((1660, 90), "violet: probably bare or smooth fields", lambda c: c[2] > c[1] + 40 and c[0] > c[1]),
        "magenta": ((510, 158), "pink-magenta: probably large building blocks", lambda c: c[0] > 170 and c[2] > 170 and c[1] < 160),
        "yellow": ((859, 194), "yellow-white: dense centre", lambda c: c[0] > 200 and c[1] > 200),
        "green": ((380, 450), "green: forest (and most mixed areas)", lambda c: c[1] > c[0] + 10 and c[1] > c[2] + 20),
    }
    d = ImageDraw.Draw(im)
    for k, ((x, y), txt, ok) in checks.items():
        c = colour(x, y)
        assert ok(c), (k, c)
        ring(d, x, y, 14, (255, 255, 255), 3)
        FACTS.setdefault("dualpol_points", {})[k] = [x, y, [int(v) for v in c]]
    offs = {"tegel": (24, 12, "la"), "violet": (-24, 30, "ra"), "magenta": (-10, 30, "la"), "yellow": (24, -40, "la"), "green": (24, 10, "la")}
    for k, ((x, y), txt, _) in checks.items():
        dx, dy, an = offs[k]
        tag(d, x + dx, y + dy, txt, font=SMALL, anchor=an)
    im.save(IMG / "14_dualpol_annot.png", optimize=True)


if __name__ == "__main__":
    geometry()
    change()
    dualpol()
    (HERE / "annot_facts.json").write_text(json.dumps(FACTS, indent=1), encoding="utf-8")
    print(json.dumps(FACTS, indent=1))
