#!/usr/bin/env python3
"""Measure text ink using mock-minus-plate so plate furniture never enters the box."""
import sys

import numpy as np
from PIL import Image

mock = np.asarray(Image.open("mock.jpg").convert("L"), dtype=float)
plate = np.asarray(Image.open("src/assets/plate.jpg").convert("L"), dtype=float)
INK = np.abs(mock - plate) > 28


def box(x0, y0, x1, y1, thresh=28):
    m = np.abs(mock[y0:y1, x0:x1] - plate[y0:y1, x0:x1]) > thresh
    if not m.any():
        return None
    ys, xs = np.nonzero(m)
    return (x0 + xs.min(), y0 + ys.min(), x0 + xs.max(), y0 + ys.max(),
            xs.max() - xs.min() + 1, ys.max() - ys.min() + 1, int(m.sum()))


def rows(x0, y0, x1, y1, min_gap=3, thresh=28, min_ink=1):
    m = np.abs(mock[y0:y1, x0:x1] - plate[y0:y1, x0:x1]) > thresh
    ink = m.sum(axis=1) >= min_ink
    out = []
    start = None
    gap = 0
    for i, v in enumerate(ink):
        if v:
            if start is None:
                start = i
            gap = 0
        else:
            if start is not None:
                gap += 1
                if gap >= min_gap:
                    out.append((y0 + start, y0 + i - gap))
                    start = None
    if start is not None:
        out.append((y0 + start, y0 + len(ink) - 1))
    for (a, b) in out:
        sub = m[a - y0:b - y0 + 1]
        ys, xs = np.nonzero(sub)
        print(f"  row y{a}..{b} h{b - a + 1}  x{x0 + xs.min()}..{x0 + xs.max()} "
              f"w{xs.max() - xs.min() + 1} ink{int(sub.sum())}")


def cols(x0, y0, x1, y1, min_gap=6, thresh=28, min_ink=1):
    m = np.abs(mock[y0:y1, x0:x1] - plate[y0:y1, x0:x1]) > thresh
    ink = m.sum(axis=0) >= min_ink
    out = []
    start = None
    gap = 0
    for i, v in enumerate(ink):
        if v:
            if start is None:
                start = i
            gap = 0
        else:
            if start is not None:
                gap += 1
                if gap >= min_gap:
                    out.append((x0 + start, x0 + i - gap))
                    start = None
    if start is not None:
        out.append((x0 + start, x0 + len(ink) - 1))
    for (a, b) in out:
        print(f"  col x{a}..{b} w{b - a + 1}")


if __name__ == "__main__":
    cmd = sys.argv[1]
    args = [int(v) for v in sys.argv[2].split(",")]
    kw = {}
    for extra in sys.argv[3:]:
        k, v = extra.split("=")
        kw[k] = int(v)
    if cmd == "box":
        print(box(*args, **kw))
    else:
        (rows if cmd == "rows" else cols)(*args, **kw)

# --- eroded mask variant used by mt2 ---
def _mask(x0, y0, x1, y1, thresh=70):
    m = np.abs(mock[y0:y1, x0:x1] - plate[y0:y1, x0:x1]) > thresh
    e = m.copy()
    e[1:, :] &= m[:-1, :]
    e[:, 1:] &= m[:, :-1]
    return e
