import sys, json, glob
import numpy as np
from PIL import Image, ImageDraw, ImageFont

# usage: fit_line.py '<json specs>' text x0,y0,x1,y1 baseline thresh
# spec: [fontfile, size, track_px]  OR [fontfile, size] to solve track

args = json.loads(sys.argv[1])
text = sys.argv[2]
x0, y0, x1, y1 = [int(v) for v in sys.argv[3].split(",")]
baseline = int(sys.argv[4])
thresh = int(sys.argv[5])
invert = len(sys.argv) > 6 and sys.argv[6] == "invert"

img = np.array(Image.open("mock.jpg").convert("L")).astype(int)
crop = img[y0:y1 + 1, x0:x1 + 1]
mockink = (crop > thresh) if not invert else (crop < thresh)
ys, xs = np.nonzero(mockink)
ml, mb = xs.min() + x0, ys.max() + y0  # ink-left, ink-bottom

W, H = x1 - x0 + 400, (y1 - y0) + 200


def render(fp, size, track, base_y):
    im = Image.new("L", (W, H), 0)
    d = ImageDraw.Draw(im)
    f = ImageFont.truetype(fp, size)
    x = 20.0
    for ch in text:
        d.text((x, base_y), ch, font=f, fill=255, anchor="ls")
        x += f.getlength(ch) + track
    return np.array(im) > 128


def score(fp, size, track):
    base_y = 100
    g = render(fp, size, track, base_y)
    gys, gxs = np.nonzero(g)
    if len(gxs) == 0:
        return 1.0
    gl = gxs.min()
    gb = gys.max()
    # place candidate so its ink-left/bottom align with the mock's in the crop
    sh = np.zeros_like(mockink)
    yy = gys + (mb - y0 - gb); xx = gxs + (ml - x0 - gl)
    ok = (yy >= 0) & (yy < sh.shape[0]) & (xx >= 0) & (xx < sh.shape[1])
    sh[yy[ok], xx[ok]] = True
    xor = (mockink ^ sh).sum(); uni = (mockink | sh).sum()
    return xor / uni


def inkheight(fp, size, track):
    g = render(fp, size, track, 100)
    ys = np.nonzero(g)[0]
    return 0 if len(ys) == 0 else ys.max() - ys.min() + 1


mock_h = ys.max() - ys.min() + 1
out = []
for spec in args:
    fp, size = spec[0], spec[1]
    if size is None:
        lo, hi = 4, 200
        for _ in range(30):
            mid = (lo + hi) / 2
            if inkheight(fp, mid, 0) < mock_h:
                lo = mid
            else:
                hi = mid
        size = round((lo + hi) / 2, 2)
    if len(spec) > 2 and spec[2] is not None:
        sc = score(fp, size, spec[2])
        out.append((sc, fp, size, spec[2]))
    else:
        best = (9.9, 0)
        for tp in [i * 0.5 for i in range(-40, 60)]:
            sc = score(fp, size, tp)
            if sc < best[0]:
                best = (sc, tp)
        sc, tp = best[0], best[1]
        for tp2 in [tp + i * 0.1 for i in range(-10, 11)]:
            s2 = score(fp, size, tp2)
            if s2 < sc:
                sc, tp = s2, tp2
        out.append((sc, fp, size, tp))
    print("%.4f %-40s size=%5.1f track=%+6.2f %+.4fem" % (out[-1][0], out[-1][1], out[-1][2], out[-1][3], out[-1][3] / out[-1][2]))
out.sort()
print("BEST", out[0])
