#!/usr/bin/env python3
"""Recover a mockup's background plate by painting the type out of it.

Mask everything brighter (or darker) than the plate, then grow the known region
inwards: at each pass, the outermost unknown ring takes the distance-weighted mean
of its known neighbours and becomes known itself. Repeat until nothing is left.

That leaves a usable reference for tone-matching generated assets, and it shows
what the background actually looks like behind the copy.

  python3 tools/inpaint.py --img mock.jpg --out work/plate.png --thresh 118
"""
import argparse

import numpy as np
from PIL import Image

OFFSETS = [(dy, dx)
           for dy in (-4, -2, 0, 2, 4)
           for dx in (-4, -2, 0, 2, 4)]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--img", default="mock.jpg")
    ap.add_argument("--out", required=True)
    ap.add_argument("--thresh", type=float, default=118,
                    help="luminance above this is treated as type")
    ap.add_argument("--dark-below", type=float, default=None)
    ap.add_argument("--dilate", type=int, default=3)
    ap.add_argument("--max-iters", type=int, default=400)
    a = ap.parse_args()

    arr = np.asarray(Image.open(a.img).convert("RGB"), dtype=np.float32)
    lum = arr.mean(axis=2)

    hole = lum > a.thresh
    if a.dark_below is not None:
        hole |= lum < a.dark_below
    for _ in range(a.dilate):
        g = hole.copy()
        g[1:, :] |= hole[:-1, :]
        g[:-1, :] |= hole[1:, :]
        g[:, 1:] |= hole[:, :-1]
        g[:, :-1] |= hole[:, 1:]
        hole = g
    print(f"masking {hole.mean() * 100:.1f}% of pixels")

    img = arr.copy()
    known = ~hole
    it = 0
    for it in range(1, a.max_iters + 1):
        acc = np.zeros_like(img)
        wsum = np.zeros(known.shape, dtype=np.float32)
        for dy, dx in OFFSETS:
            acc += np.roll(np.roll(img * known[..., None], dy, 0), dx, 1)
            wsum += np.roll(np.roll(known.astype(np.float32), dy, 0), dx, 1)
        w = wsum > 0
        newly = (~known) & w
        if not newly.any():
            break
        img[newly] = (acc / np.maximum(wsum, 1e-6)[..., None])[newly]
        known |= newly
    print(f"filled in {it} passes, {np.unravel_index(0, (0,)) if False else ''}"
          f"{('still ' + str(int((~known).sum())) + ' px unknown') if (~known).any() else 'complete'}")

    out = Image.fromarray(np.clip(img, 0, 255).astype(np.uint8))
    out.save(a.out)
    g = np.asarray(out.convert("L"), dtype=np.float32)
    print("plate lum p1/p50/p95/p99: "
          + " ".join(f"{np.percentile(g, q):5.1f}" for q in (1, 50, 95, 99)))
    print("wrote", a.out, out.size)


if __name__ == "__main__":
    main()
