#!/usr/bin/env python3
"""ruleprobe - measure the print-size rules a line drawing needs so a digital
fill doesn't cross it.

Two synthetic sweeps at 300 dpi, rendered the way a vector illustration
exports (4x supersample, then LANCZOS down):

  A. wall width: two rooms separated by a black wall of width w px at 300 dpi.
     For which fill tolerances does the fill cross?
  B. joint shortfall: two rooms separated by walls that should meet at a
     corner; the vertical wall stops d px short. For which d / tolerance does
     the fill cross?

Fill semantics match gapfill.py: fillable pixels are >= FILL_T (near-white),
8-connected. FILL_T=225 is an ordinary bucket fill (12% tolerance from white);
245 is tight, 200 is loose.

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

S = 4  # supersample factor
TOLS = [250, 245, 240, 230, 225, 210, 200, 180, 160, 128, 100]
S8 = np.ones((3, 3), bool)


def render(w, h, rects):
    """rects: list of (x0, y0, x1, y1) floats in native px. Black on white."""
    im = Image.new("L", (w * S, h * S), 255)
    d = ImageDraw.Draw(im)
    for (x0, y0, x1, y1) in rects:
        d.rectangle([x0 * S, y0 * S, x1 * S - 1, y1 * S - 1], fill=0)
    return np.array(im.resize((w, h), Image.LANCZOS), dtype=np.uint8, copy=True)


def fill_reaches(img, seed_xy, target_xy, fill_t):
    """seed/target are (x, y) in native px."""
    free = img >= fill_t
    lab, _ = ndimage.label(free, structure=S8)
    sx, sy = seed_xy
    tx, ty = target_xy
    sl, sr = lab[sy, sx], lab[ty, tx]
    return bool(sl and sr and sl == sr)


def max_tol_crossed(img, seed, target):
    """Highest fill_t (tightest fill) at which the fill still crosses."""
    crossed = [t for t in TOLS if fill_reaches(img, seed, target, t)]
    return max(crossed) if crossed else None


def wall_sweep():
    rows = []
    w_px, h_px = 500, 400
    y0, y1 = 0.0, float(h_px)
    for w in [0.5, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0]:
        for off in (0.0, 0.5):
            x0 = 250.0 + off
            img = render(w_px, h_px, [(x0, y0, x0 + w, y1)])
            mt = max_tol_crossed(img, (120, 200), (380, 200))
            # darkest pixel on the wall's narrowest row
            col = int(round(x0 + w / 2))
            darkest = int(img[200, max(0, col - 2):col + 3].min())
            rows.append({"w_px": w, "offset": off, "crosses_up_to_t": mt,
                         "holds_at_225": (mt is None or mt < 225),
                         "wall_min_grey": darkest})
    return rows


def joint_sweep():
    rows = []
    w_px, h_px = 700, 700
    t = 3.0          # wall thickness, solid
    yj = 400.0       # horizontal wall top edge
    xj = 300.0       # vertical wall left edge
    for d in [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 6.0]:
        for off in (0.0, 0.5):
            rects = [
                (0.0, yj, w_px, yj + t),              # horizontal wall
                (xj, 0.0, xj + t, yj - d + off),      # vertical wall, stops d short
            ]
            img = render(w_px, h_px, rects)
            mt = max_tol_crossed(img, (120, 200), (560, 200))
            # grey of the worst corridor pixel: scan the corridor column band
            band = img[int(yj - d - 2):int(yj + 1), int(xj + t + 2):int(xj + t + 40)]
            worst = int(band.min()) if band.size else None
            rows.append({"shortfall_px": d, "offset": off, "crosses_up_to_t": mt,
                         "holds_at_225": (mt is None or mt < 225),
                         "corridor_min_grey": worst})
    return rows


def control_sweep():
    """Sealed joint, no shortfall, thicker walls: must hold at every tolerance."""
    rows = []
    for t in [2.0, 3.0, 4.0]:
        img = render(700, 700, [(0.0, 400.0, 700, 400 + t), (300.0, 0.0, 300 + t, 400 + t)])
        rows.append({"thickness": t, "crosses_up_to_t": max_tol_crossed(img, (120, 200), (560, 200))})
    return rows


if __name__ == "__main__":
    out = {"wall": wall_sweep(), "joint": joint_sweep(), "sealed_control": control_sweep(),
           "tols_tried": TOLS, "fill_semantics": "fillable = grey >= FILL_T; 225 = 12% tolerance from white"}
    print(json.dumps(out, indent=1))
    json.dump(out, open("ruleprobe.json", "w"), indent=1)