#!/usr/bin/env bash
# Check the *rendered output* is laid out correctly by this distro's render stack, not just that
# rendering runs. An activity block must fill most of its day lane on the cross axis - the column
# width in the vertical layout, the row height in the horizontal one. That cross axis is sized as a
# % of a lane track, and if the track has no definite size the block collapses to its label (a grid
# 1fr track does exactly that: on the width axis only below WeasyPrint 62, on the height axis even
# on 62). This fails while `smoke` still passes, pointing at the installed render library rather
# than at timeglance. Output-based (reads back the rasterised pixels), so WeasyPrint-independent.
set -euo pipefail

python3 - <<'PY'
import subprocess
import tempfile
from pathlib import Path

from PIL import Image

from timeglance.weekly import build as wb

cfg = {
    "title": "t",
    "days": ["Mon"],  # a single lane spans almost the whole sheet on the cross axis
    "day_start": "08:00",
    "day_end": "18:00",
    "topics": {"x": {"label": "X", "color": "#ff0000", "visible": True}},
    "activities": [{"topic": "x", "days": ["Mon"], "start": "09:00", "end": "17:00"}],
}
for layout in ("vertical", "horizontal"):
    tmp = Path(tempfile.mkdtemp())
    (tmp / "s.pdf").write_bytes(wb.render_pdf(cfg, None, "A4", layout=layout))
    subprocess.run(
        ["pdftocairo", "-png", "-singlefile", "-scale-to-x", "1200", "-scale-to-y", "-1", str(tmp / "s.pdf"), str(tmp / "s")],
        check=True,
    )
    img = Image.open(tmp / "s.png").convert("RGB")
    w, h = img.size
    px = img.load()
    xs = []
    ys = []
    for y in range(h):
        for x in range(w):
            r, g, b = px[x, y]
            if r > 180 and g < 80 and b < 80:
                xs.append(x)
                ys.append(y)
    assert xs, f"{layout}: no activity block rendered"
    # Cross axis = the lane dimension the block should fill: width for vertical, height for horizontal.
    cross, extent = (max(xs) - min(xs), w) if layout == "vertical" else (max(ys) - min(ys), h)
    assert cross > 0.3 * extent, f"{layout}: block only {cross}px on its cross axis of {extent} - it collapsed"
    print(f"{layout}: block fills {cross}px of {extent} on the cross axis (OK)")
PY

echo "render-correctness test OK"
