#!/usr/bin/env python3
"""gapfill - what a bucket fill at a given tolerance actually does to line art.

Same regions as gaptest.py, then one extra step: simulate the fill.
Fill rule: pixels >= FILL_T are "fillable" (white-ish), pixels below are wall.
Every fillable component gets one colour. Regions that share a colour at that
tolerance are regions your bucket fill will merge, i.e. colour bleeds from one
into the other.

Writes a 3-panel PNG: original | verdict map | fill at tolerance.

Terminology, 2026. MIT, same terms as gaptest.py.
"""
import sys, json
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from scipy import ndimage
import gaptest as G


def colours(n):
    """Distinct, readable hues, in a stable order."""
    out = []
    for i in range(n):
        h = (i * 0.61803398875) % 1.0          # golden-ratio hue walk
        s, v = 0.62, 0.92
        i6 = int(h * 6)
        f = h * 6 - i6
        p, q, t = v * (1 - s), v * (1 - f * s), v * (1 - (1 - f) * s)
        rgb = [(v, t, p), (q, v, p), (p, v, t), (p, q, v), (t, p, v), (v, p, q)][i6 % 6]
        out.append(tuple(int(c * 255) for c in rgb))
    return out


def fill_sim(img, rep, base, fill_t=225):
    h, w = img.shape
    lab, n = ndimage.label(img >= fill_t, structure=G.S8)
    # a region belongs to the fill component that owns MOST OF ITS OWN PIXELS.
    # (its centroid can sit in a neighbour when the region is a thin crescent)
    comp = {}
    for o in rep["regions"]:
        if o["is_background"]:
            continue
        m = base == o["id"]
        if not m.any():
            continue
        vals = lab[m]
        vals = vals[vals > 0]
        if len(vals) == 0:
            continue
        c = int(np.bincount(vals).argmax())
        comp.setdefault(c, []).append(o["id"])
    merged = {c: ids for c, ids in comp.items() if len(ids) > 1}
    rgb = np.stack([img] * 3, -1).astype(np.uint8)
    pal = colours(max(1, len(comp)))
    # paper stays white-ish; every other component gets its own colour
    border = np.concatenate([lab[0, :], lab[-1, :], lab[:, 0], lab[:, -1]])
    border = border[border > 0]
    vals, cnts = np.unique(border, return_counts=True)
    bg_lab = int(vals[np.argmax(cnts)]) if len(vals) else 0
    for k, (c, ids) in enumerate(sorted(comp.items(), key=lambda kv: -len(kv[1]))):
        if c == bg_lab:
            continue
        m = lab == c
        rgb[m] = pal[k % len(pal)]
    return rgb, merged, lab, bg_lab


def panel(arr, width, label, font, legend=None):
    im = Image.fromarray(arr.astype(np.uint8)).convert("RGB")
    if im.width > width:
        im = im.resize((width, int(im.height * width / im.width)), Image.LANCZOS)
    strip = Image.new("RGB", (im.width, im.height + 34), (18, 18, 18))
    strip.paste(im, (0, 34))
    d = ImageDraw.Draw(strip)
    d.text((8, 9), label, fill=(235, 235, 235), font=font)
    if legend:
        x = 8 + font.getlength(label) + 16
        small = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 16)
        for colour, word in legend:
            d.rectangle([x, 13, x + 12, 25], fill=colour)
            d.text((x + 17, 10), word, fill=(220, 220, 220), font=small)
            x += 17 + small.getlength(word) + 14
    return strip


def main():
    src = sys.argv[1] if len(sys.argv) > 1 else "outside/tenniel05a.jpg"
    out = sys.argv[2] if len(sys.argv) > 2 else "gapfill.png"
    jout = sys.argv[3] if len(sys.argv) > 3 else "gapfill.json"
    fill_t = int(sys.argv[4]) if len(sys.argv) > 4 else 225
    img, _resized = G.load_gray(src, 0)   # native resolution: resampling opens thin walls
    rep = G.analyze(img)
    c = rep["counts"]

    # verdict map
    vmap = np.stack([img] * 3, -1).astype(np.uint8)
    colr = {"open": (222, 48, 44), "faint": (236, 168, 24), "sealed": (32, 150, 92)}
    base, _ = ndimage.label(img >= G.T_START, structure=G.S8)
    for o in rep["regions"]:
        if o["is_background"]:
            continue
        m = (base == o["id"]) & (img >= 200)
        vmap[m] = (0.40 * vmap[m] + 0.60 * np.array(colr[o["verdict"]])).astype(np.uint8)

    frgb, merged, lab, bg_lab = fill_sim(img, rep, base, fill_t)
    into_paper = sum(len(v) for k, v in merged.items() if k == bg_lab)
    with_other = sum(len(v) for k, v in merged.items() if k != bg_lab)

    fnt = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 22)
    W = 620
    p1 = panel(np.stack([img] * 3, -1), W, "the drawing", fnt)
    p2 = panel(vmap, W, "gaptest verdicts", fnt,
               legend=[(colr["sealed"], f"sealed {c['sealed']}"),
                       (colr["faint"], f"faint {c['faint']}"),
                       (colr["open"], f"open {c['open']}")])
    p3 = panel(frgb, W,
               f"t={fill_t}: {into_paper} leak to paper, {with_other} merge", fnt)
    gap = 10
    H = max(p.height for p in (p1, p2, p3))
    canvas = Image.new("RGB", (W * 3 + gap * 2, H), (18, 18, 18))
    for i, p in enumerate((p1, p2, p3)):
        canvas.paste(p, (i * (W + gap), 0))
    canvas.save(out)

    report = {
        "image": src, "size": [int(img.shape[1]), int(img.shape[0])],
        "counts": c, "fill_t": fill_t,
        "regions_touching_another_at_fill_t": with_other,
        "regions_running_into_paper_at_fill_t": into_paper,
        "merge_groups": [{"component": int(k), "paper": k == bg_lab, "regions": v}
                         for k, v in merged.items()],
        "paper": G.paper_stats(img),
    }
    with open(jout, "w") as f:
        json.dump(report, f, indent=1)
    print(json.dumps({k: report[k] for k in
                      ("counts", "fill_t", "regions_touching_another_at_fill_t",
                       "regions_running_into_paper_at_fill_t")}))
    print("panels:", canvas.size)


if __name__ == "__main__":
    main()