#!/usr/bin/env python3
"""Render src/index.html and compare it against mock.jpg.

Usage: python3 tools/shot.py [--label NAME] [--width W] [--height H] [--zoom Z]

Writes into shots/:
  <label>.png              the render
  <label>.compare.png      mock | render side by side
  <label>.edges.png        mock edges (cyan) over render edges (red)
  <label>.stack.png        vertical stack: mock above render
Portrait crops of any misaligned region are for humans to look at.
"""
import argparse
import os
import subprocess
import sys

import numpy as np
from PIL import Image, ImageChops, ImageFilter

ROOT = (os.environ.get("MOCKUP_ROOT")
        or os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
MOCK = os.path.join(ROOT, "mock.jpg")
SRC = os.path.join(ROOT, "src", "index.html")  # override with --src
SHOTS = os.path.join(ROOT, "shots")

MOCK_W = MOCK_H = None


def render(out_path, width, height, zoom, hide=(), src=None):
    from playwright.sync_api import sync_playwright

    with sync_playwright() as p:
        b = p.chromium.launch(args=["--force-color-profile=srgb",
                                    "--font-render-hinting=none",
                                    "--disable-lcd-text"])
        pg = b.new_page(viewport={"width": width, "height": height},
                        device_scale_factor=zoom)
        pg.goto("file://" + (src or SRC))
        if hide:
            pg.add_style_tag(content=",".join(hide) + "{display:none!important}")
        # BODY-OFFSET: a margin that collapses out of body displaces every
        # absolutely positioned child without changing anything visible.
        _by = pg.evaluate("() => document.body.getBoundingClientRect().y")
        if abs(_by) > 0.5:
            print(f"  !! body.y = {_by:.0f} - margin collapsed out of body; "
                  f"absolute children are displaced by that much. Add display:flow-root.")
        # ANCHOR-CHECK: an absolute child resolves against the nearest
        # positioned ancestor. `.hero` is usually positioned for z-index, so a
        # page-anchored list placed inside it lands at the wrong y and overlaps
        # whatever is there -- and the MAE barely notices, because a small text
        # block is a tiny fraction of the page.
        _anchors = pg.evaluate('''() => {
          const out = [];
          document.querySelectorAll('body *').forEach(e => {
            const cs = getComputedStyle(e);
            if (cs.position !== 'absolute') return;
            if (cs.top === 'auto' && cs.bottom === 'auto') return;
            const op = e.offsetParent;
            if (!op || op.tagName === 'BODY' || op.tagName === 'HTML') return;
            out.push((e.className || e.tagName) + ' -> .' + (op.className || op.tagName));
          });
          return [...new Set(out)];
        }''')
        if _anchors:
            print(f"  ?? absolute element(s) anchored to a section, not body: "
                  f"{', '.join(_anchors[:3])}")
        pg.wait_for_timeout(300)
        try:
            pg.evaluate("document.fonts.ready")
        except Exception:
            pass
        pg.wait_for_timeout(200)
        pg.screenshot(path=out_path)
        b.close()


def edges(im, blur=1.2):
    g = im.convert("L").filter(ImageFilter.GaussianBlur(blur))
    a = np.asarray(g, dtype=np.float32)
    gx = np.zeros_like(a)
    gy = np.zeros_like(a)
    gx[:, 1:-1] = a[:, 2:] - a[:, :-2]
    gy[1:-1, :] = a[2:, :] - a[:-2, :]
    m = np.hypot(gx, gy)
    m = np.clip(m / max(1e-6, np.percentile(m, 99.5)), 0, 1)
    return m


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--label", default="latest")
    ap.add_argument("--width", type=int, default=None)
    ap.add_argument("--height", type=int, default=None)
    ap.add_argument("--zoom", type=float, default=1.0)
    ap.add_argument("--src", default=None, help="html file to render")
    ap.add_argument("--mock", default=None, help="reference mockup image")
    ap.add_argument("--hide", default=None,
                    help="comma separated selectors to hide, for isolating elements"
                         " when measuring")
    args = ap.parse_args()

    ref = Image.open(args.mock or MOCK)
    if args.width is None:
        args.width = ref.size[0]
    if args.height is None:
        args.height = ref.size[1]

    os.makedirs(SHOTS, exist_ok=True)
    out = os.path.join(SHOTS, args.label + ".png")
    hide = [s.strip() for s in (args.hide or "").split(",") if s.strip()]
    render(out, args.width, args.height, args.zoom, hide, args.src)

    mock = Image.open(args.mock or MOCK).convert("RGB")
    ren = Image.open(out).convert("RGB")
    if ren.size != mock.size:
        ren = ren.resize(mock.size, Image.LANCZOS)
        ren.save(os.path.join(SHOTS, args.label + ".norm.png"))

    # side by side
    gap = 16
    cw, ch = mock.size
    sxs = Image.new("RGB", (cw * 2 + gap, ch), (20, 20, 20))
    sxs.paste(mock, (0, 0))
    sxs.paste(ren, (cw + gap, 0))
    sxs.save(os.path.join(SHOTS, args.label + ".compare.png"))

    # stacked (better for narrow viewing)
    st = Image.new("RGB", (cw, ch * 2 + gap), (20, 20, 20))
    st.paste(mock, (0, 0))
    st.paste(ren, (0, ch + gap))
    st.save(os.path.join(SHOTS, args.label + ".stack.png"))

    # edge overlay
    em, er = edges(mock), edges(ren)
    ov = np.zeros((ch, cw, 3), dtype=np.uint8)
    ov[..., 0] = (er * 255).astype(np.uint8)          # render  -> red
    ov[..., 1] = (em * 130).astype(np.uint8)          # mock    -> green
    ov[..., 2] = (em * 255).astype(np.uint8)          # mock+green -> cyan
    Image.fromarray(ov).save(os.path.join(SHOTS, args.label + ".edges.png"))

    # numeric report
    a = np.asarray(mock, dtype=np.float32)
    b = np.asarray(ren, dtype=np.float32)
    mae = np.abs(a - b).mean()
    print(f"render {ren.size}  MAE {mae:6.2f}  (mock {mock.size})")

    # coarse 4x3 grid of MAE, to point at the worst region
    hh, ww = ch // 3, cw // 4
    cells = []
    for r in range(3):
        row = []
        for c in range(4):
            sub_a = a[r * hh:(r + 1) * hh, c * ww:(c + 1) * ww]
            sub_b = b[r * hh:(r + 1) * hh, c * ww:(c + 1) * ww]
            row.append(f"{np.abs(sub_a - sub_b).mean():5.1f}")
        cells.append(" ".join(row))
    print("MAE grid (4 cols x 3 rows):")
    for r in cells:
        print("   ", r)


if __name__ == "__main__":
    main()
