#!/usr/bin/env python3
"""Recover a background plate from a comp by editing the type out of it.

The plate is the comp with the page's own typesetting removed, so that real HTML
text can sit on it. The hard part is what counts as "the page's own typesetting":
a headline is, but the print on a coffee bag and the signage on a building are
not — they are the subject, and removing them changes the object. This tool exists
so a prompt can be iterated against real comps instead of guessed at.

  python3 tools/plate.py --comp mock.jpg --prompt-file work/decompose.txt \
      --out work/plate-test.jpg

Costs one reference-image call at low quality (~$0.02 at 1536x864).
"""
import argparse
import base64
import json
import os
import sys
import urllib.request

CFG_CANDIDATES = [
    os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config.json"),
    "/home/ubuntu/sampler/config.json",
]
ROOT = os.environ.get("MOCKUP_ROOT") or os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def api_key():
    for path in CFG_CANDIDATES:
        try:
            return json.load(open(path))["openrouter_api_key"]
        except Exception:
            continue
    if os.environ.get("OPENROUTER_API_KEY"):
        return os.environ["OPENROUTER_API_KEY"]
    sys.exit("no OpenRouter key: set OPENROUTER_API_KEY or provide config.json")


def data_url(path, mime="image/jpeg"):
    return f"data:{mime};base64," + base64.b64encode(open(path, "rb").read()).decode()


def build_mask(comp, art_region):
    """Mask the page's own type so the rest of the frame is never touched.

    A full-frame re-render drifts flat colours by several levels and can delete
    text that belongs to the subject (a product label, building signage). Masking
    the type makes both impossible: everything outside the mask is preserved by
    construction, so only the type is repainted.
    """
    import io
    import numpy as np
    from PIL import Image, ImageFilter
    a = np.asarray(Image.open(comp).convert("RGB"), dtype=np.float32)
    lum = a.mean(axis=2)
    mid = (np.percentile(lum, 2) + np.percentile(lum, 98)) / 2
    dark = lum < mid
    ink = dark if dark.mean() < 0.5 else ~dark      # ink is the minority class
    if art_region:
        x0, y0, x1, y1 = [int(v) for v in art_region.split(",")]
        art = np.zeros_like(ink)
        art[y0:y1, x0:x1] = True
        ink = ink & ~art
    m = Image.fromarray((ink.astype(np.uint8) * 255)).filter(ImageFilter.MaxFilter(15))
    buf = io.BytesIO()
    m.save(buf, format="PNG")
    print(f"mask: {100 * (np.asarray(m) > 0).mean():.1f}% of the frame")
    return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()


def verify(comp, plate, mask_png_or_url):
    """How much of the type survived inside the mask.

    The MAE cannot answer this. A plate that keeps the original type matches the
    comp *better* than one that removes it, so the score improves while the plate
    is wrong and the built page shows doubled text. Measure residual ink instead.
    """
    import io
    import numpy as np
    from PIL import Image
    if mask_png_or_url.startswith("data:"):
        raw = base64.b64decode(mask_png_or_url.split(",", 1)[1])
        mask = np.asarray(Image.open(io.BytesIO(raw)).convert("L")) > 128
    else:
        mask = np.asarray(Image.open(mask_png_or_url).convert("L")) > 128
    a = np.asarray(Image.open(comp).convert("L"), dtype=np.float32)
    b = np.asarray(Image.open(plate).convert("L"), dtype=np.float32)
    mid = (np.percentile(a, 2) + np.percentile(a, 98)) / 2
    ink_a = (a > mid) if (a > mid).mean() < 0.5 else (a < mid)
    ink_b = (b > mid) if (a > mid).mean() < 0.5 else (b < mid)
    before = (ink_a & mask).sum()
    after = (ink_b & mask).sum()
    pct = 100.0 * after / max(1, before)
    print(f"residual type inside mask: {after}/{before} px = {pct:.1f}%")
    if pct > 15:
        print("  !! too much type survived — the page will show doubled text. "
              "Re-run, or raise --mask dilation / strengthen the prompt.")
    return pct


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--comp", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--prompt", default=None)
    ap.add_argument("--prompt-file", default=None)
    ap.add_argument("--model", default="openai/gpt-image-2.6-flare")
    ap.add_argument("--quality", default="low")
    ap.add_argument("--mask", default="auto",
                    help="auto (default): mask the page's type and edit only there; "
                         "'none' to re-render the whole frame; or a mask PNG path")
    ap.add_argument("--art-region", default=None,
                    help="x0,y0,x1,y1 of the photographed/illustrated area, excluded "
                         "from an auto mask so its own text is never edited")
    ap.add_argument("--size", default=None, help="default: the comp's own pixel size")
    a = ap.parse_args()

    prompt = a.prompt or (open(a.prompt_file).read() if a.prompt_file else None)
    if not prompt:
        sys.exit("pass --prompt or --prompt-file")

    from PIL import Image
    w, h = Image.open(a.comp).size
    size = a.size or f"{w}x{h}"

    mask_url = None
    if a.mask == "auto":
        mask_url = build_mask(a.comp, a.art_region)
    elif a.mask != "none":
        mask_url = data_url(a.mask, "image/png")

    body = {
        "model": a.model,
        "prompt": prompt,
        "n": 1,
        "quality": a.quality,
        "size": size,
        "output_format": "jpeg",
        "input_references": [{"type": "image_url", "image_url": {"url": data_url(a.comp)}}],
    }
    req = urllib.request.Request(
        "https://openrouter.ai/api/v1/images",
        data=json.dumps(body).encode(),
        headers={"Authorization": "Bearer " + api_key(), "Content-Type": "application/json"},
    )
    j = json.load(urllib.request.urlopen(req, timeout=240))
    if mask_url:
        body["mask"] = mask_url
    if j.get("error"):
        sys.exit("provider error: " + str(j["error"])[:300])
    b64 = j["data"][0].get("b64_json")
    if not b64:
        sys.exit("no image in response")
    open(a.out, "wb").write(base64.b64decode(b64))
    u = j.get("usage", {})
    print(f"wrote {a.out}  {size}  cost=${u.get('cost', '?')}  "
          f"tokens={u.get('completion_tokens_details', {}).get('image_tokens', '?')}")
    if mask_url:
        verify(a.comp, a.out, mask_url)


if __name__ == "__main__":
    main()
