"""Crop the white margins off the exercise and answer-key figures for the interactive module.
The two source figures share one layout (axes x 303-1346, panel tops 161/617/1073, 404 px tall),
so the same crop keeps them aligned. learn.html's GEO constants assume CROP below."""
import pathlib
import numpy as np
from PIL import Image

IMG = pathlib.Path(__file__).resolve().parent.parent / "img"
CROP = (296, 128, 1354, 1484)  # left, top, right, bottom in source pixels

for src, dst in (("06_exercise.png", "06_exercise_mark.png"), ("07_answer_key.png", "07_answer_key_mark.png")):
    im = Image.open(IMG / src)
    assert im.size == (1650, 1530), im.size
    im = im.convert("RGB").crop(CROP)
    if dst.startswith("07"):
        # the "still there" circles render cream (228,223,199), too close to the white "in A" circles:
        # push cream-tinted pixels (r~g, b clearly lower) towards saturated yellow, keeping antialiasing
        a = np.asarray(im).astype(float)
        r, g, b = a[..., 0], a[..., 1], a[..., 2]
        t = np.clip((r - b - 6) / 23.0, 0, 1) * (np.abs(r - g) < 14) * (r > 110)
        target = np.array([255.0, 205.0, 0.0])
        a = a + t[..., None] * (target - np.array([228.0, 223.0, 199.0]))
        im = Image.fromarray(np.clip(a, 0, 255).astype("uint8"))
        print("recoloured pixels:", int((t > 0).sum()))
        # the key table refers to columns 1-5: draw the same column lines as the exercise image
        # (in the crop, data column x sits at 7 + (x + 0.5) * 1044/440; panels start at y = 33, 489, 945, 404 px tall)
        from PIL import ImageDraw, ImageFont
        d = ImageDraw.Draw(im)
        try:
            font = ImageFont.truetype("arialbd.ttf", 18)
        except OSError:
            font = ImageFont.load_default()
        for top in (33, 489, 945):
            for gx in range(0, 440, 100):
                x = 7 + (gx + 0.5) * 1044 / 440
                d.line([(x, top), (x, top + 403)], fill=(255, 216, 77), width=2)
                d.rounded_rectangle([x + 3, top + 4, x + 25, top + 30], 4, fill=(0, 0, 0))
                d.text((x + 8, top + 6), str(gx // 100 + 1), fill=(255, 216, 77), font=font)
    im.save(IMG / dst, optimize=True)
    print(dst, im.size)

# landing-page hero: the Tollerort pair (row 1) of the lesson 13 close-up figure, with its credit
# burned in below, so the licence travels with the image when it is shared on its own
HERO_CREDIT = ("Left: contains modified Copernicus Sentinel data (2026). Right: ICEYE SAR Open Dataset (c) ICEYE, CC BY 4.0, "
               "modified by David Reid. Dashed line (c) OpenStreetMap contributors, ODbL.")


def with_credit(im, text, size=22):
    from PIL import ImageDraw, ImageFont
    try:
        font = ImageFont.truetype("arial.ttf", size)
    except OSError:
        font = ImageFont.load_default()
    lines, cur = [], ""
    for w in text.split(" "):  # wrap to the image width, measured in the actual font
        trial = (cur + " " + w).strip()
        if font.getlength(trial) > im.width - 16 and cur:
            lines.append(cur); cur = w
        else:
            cur = trial
    lines.append(cur)
    lh = size + 6
    out = Image.new("RGB", (im.width, im.height + lh * len(lines) + 10), "white")
    out.paste(im.convert("RGB"), (0, 0))
    d = ImageDraw.Draw(out)
    for k, ln in enumerate(lines):
        d.text((im.width - 8, im.height + 6 + k * lh), ln, fill=(90, 100, 112), font=font, anchor="ra")
    return out


im = Image.open(IMG / "10_iceye_zoom.png")
assert im.size == (1800, 1860), im.size
hero = im.crop((64, 195, 1735, 990))
with_credit(hero, HERO_CREDIT).save(IMG / "hero_tollerort.png", optimize=True)
print("hero_tollerort.png", hero.size, "+ credit strip")
