#!/usr/bin/env python3
"""Match a generated asset to a reference plate taken from the mockup.

Recover the plate by inpainting the type out of the mockup (see tools/inpaint.py),
then remap the generated image onto it by *rank*: each source pixel gets the
colour the reference has at the same percentile. That transfers tone, contrast
and hue in one step and keeps the asset's own structure intact, which is a lot
more faithful than stacking CSS filters until it looks close.

  python3 tools/matchplate.py --src work/bg-gen.png --ref work/plate.png \
      --width 1536 --height 864 --out src/assets/map.png
"""
import argparse

import numpy as np
from PIL import Image


def ranks(x):
    """Percentile rank of every element, in [0, 1]."""
    flat = x.ravel()
    order = flat.argsort()
    r = np.empty(flat.size, dtype=np.float32)
    r[order] = np.linspace(0, 1, flat.size, dtype=np.float32)
    return r.reshape(x.shape)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--src", required=True)
    ap.add_argument("--ref", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--width", type=int, default=None)
    ap.add_argument("--height", type=int, default=None)
    ap.add_argument("--bins", type=int, default=512)
    ap.add_argument("--gain", type=float, default=1.0,
                    help="<1 flattens the transferred contrast")
    ap.add_argument("--ref-cap", type=float, default=98.0,
                    help="ignore the reference's brightest pixels (leftover type)")
    a = ap.parse_args()

    src = Image.open(a.src).convert("RGB")
    if a.width and a.height:
        sw, sh = src.size
        k = max(a.width / sw, a.height / sh)
        src = src.resize((max(a.width, int(sw * k + 0.5)),
                          max(a.height, int(sh * k + 0.5))), Image.LANCZOS)
        sw, sh = src.size
        left, top = (sw - a.width) // 2, (sh - a.height) // 2
        src = src.crop((left, top, left + a.width, top + a.height))

    ref = Image.open(a.ref).convert("RGB").resize(src.size, Image.LANCZOS)

    rs = ranks(np.asarray(src.convert("L"), dtype=np.float32))
    ra = np.asarray(ref, dtype=np.float32).reshape(-1, 3)
    rl = np.asarray(ref.convert("L"), dtype=np.float32).ravel()
    order = rl.argsort()
    ra = ra[order]
    cut = int(ra.shape[0] * a.ref_cap / 100.0)
    ra, rl = ra[:cut], rl[:cut]

    edges = np.linspace(0, ra.shape[0], a.bins + 1).astype(int)
    lut = np.stack([ra[edges[i]:max(edges[i] + 1, edges[i + 1])].mean(axis=0)
                    for i in range(a.bins)])
    # flatten the LUT's contrast about its own mean if asked
    if a.gain != 1.0:
        mu = lut.mean(axis=0)
        lut = mu + (lut - mu) * a.gain

    idx = np.clip((rs * (a.bins - 1)).round().astype(int), 0, a.bins - 1)
    out = lut[idx]
    img = Image.fromarray(np.clip(out, 0, 255).astype(np.uint8))
    img.save(a.out)

    g = np.asarray(img.convert("L"), dtype=np.float32)
    print("out lum p1/p25/p50/p75/p99: "
          + " ".join(f"{np.percentile(g, q):5.1f}" for q in (1, 25, 50, 75, 99)))
    r = np.asarray(ref.convert("L"), dtype=np.float32)
    print("ref lum p1/p25/p50/p75/p99: "
          + " ".join(f"{np.percentile(r, q):5.1f}" for q in (1, 25, 50, 75, 99)))
    print("wrote", a.out, img.size)


if __name__ == "__main__":
    main()
