#!/usr/bin/env python3
"""Tone-match a generated asset to a reference region of the mockup.

A generated background rarely lands on the mockup's exact contrast and hue. Rather
than eyeball CSS filters, map the asset's luminance distribution onto the darkness
range measured from the mockup, and tint onto a two-stop ramp picked from it.

  python3 tools/tone.py --src work/bg-gen.png --mock mock.jpg \
      --mock-region 40,100,1500,860 --ramp 3,60,58 --ramp 40,92,86 \
      --out assets/map.png --width 1536 --height 864
"""
import argparse

import numpy as np
from PIL import Image


def pct_range(lum, lo=1.0, hi=99.0):
    return np.percentile(lum, lo), np.percentile(lum, hi)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--src", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--mock", default="mock.jpg")
    ap.add_argument("--mock-region", default="0,0,100000,100000")
    ap.add_argument("--ramp", action="append", default=[], type=str,
                    help="'r,g,b' dark and light ends of the duotone; pass twice")
    ap.add_argument("--width", type=int, default=None)
    ap.add_argument("--height", type=int, default=None)
    ap.add_argument("--lo", type=float, default=1.0)
    ap.add_argument("--hi", type=float, default=99.0)
    a = ap.parse_args()

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

    mock = Image.open(a.mock).convert("RGB")
    x0, y0, x1, y1 = [int(v) for v in a.mock_region.split(",")]
    x1, y1 = min(x1, mock.width), min(y1, mock.height)
    m = mock.crop((x0, y0, x1, y1))
    mlum = np.asarray(m.convert("L"), dtype=np.float32)
    m_lo, m_hi = pct_range(mlum, a.lo, a.hi)

    g = np.asarray(src.convert("L"), dtype=np.float32)
    s_lo, s_hi = pct_range(g, a.lo, a.hi)
    print(f"mock plate lum {m_lo:.0f}..{m_hi:.0f}   asset lum {s_lo:.0f}..{s_hi:.0f}")

    if a.ramp:
        cols = [np.array([float(v) for v in r.split(",")]) for r in a.ramp]
    else:
        # sample the mockup's own darkest and lightest plate colours
        arr = np.asarray(m, dtype=np.float32)
        flat = arr.reshape(-1, 3)
        l = flat.mean(axis=1)
        cols = [flat[l <= np.percentile(l, 6)].mean(axis=0),
                flat[l >= np.percentile(l, 90)].mean(axis=0)]
    print("ramp", [tuple(c.round().astype(int)) for c in cols])

    t = np.clip((g - s_lo) / max(1e-6, s_hi - s_lo), 0, 1)[..., None]
    out = cols[0][None, None, :] + (cols[1] - cols[0])[None, None, :] * t
    img = Image.fromarray(np.clip(out, 0, 255).astype(np.uint8))
    img.save(a.out)
    print("wrote", a.out, img.size)


if __name__ == "__main__":
    main()
