#!/usr/bin/env python3
"""make-figs.py <workdir>: draw the two code-drawn figures of etsy-listing-photo-size from the run files.
Reads <workdir>/test-results.txt (section 3) and <workdir>/crop-all.jsonl, writes
<workdir>/fig/bytes-chart.html and <workdir>/fig/crop-zones.html (1200 px wide, text 28 px or more)."""
import base64, json, os, re, subprocess, sys

W = sys.argv[1] if len(sys.argv) > 1 else ""
if not W or not os.path.isfile(os.path.join(W, "test-results.txt")):
    sys.exit("usage: make-figs.py <workdir> (needs test-results.txt and crop-all.jsonl)")
os.makedirs(os.path.join(W, "fig"), exist_ok=True)
rows = {}
for line in open(os.path.join(W, "test-results.txt"), encoding="utf-8", newline="").read().splitlines():
    m = re.match(r"out/(t950|t1mb)/([a-z-]+)-\d+kb\.jpg \| (\d+) \| (\d+)x(\d+) \| (?:\d+|none) \| (\d+)x(\d+)", line)
    if m:
        rows.setdefault(m.group(2), {})[m.group(1)] = (int(m.group(3)), f"{m.group(6)} x {m.group(7)}")
names = {"candle-wax": "Candle wax", "decorative-candle": "Candle gift box", "duck-mug": "Duck mug", "toy-train": "Wooden tracks"}
order = [k for k in names if k in rows]
if len(order) != 4:
    sys.exit(f"expected 4 photos in test-results.txt, found {order}")

# Figure 1: bytes per photo, typed 950 KB vs the 1 MB button, with the 1,000,000-byte line.
X0, SCALE = 430, 640 / 1_100_000
H = 230 + len(order) * 150 + 90
s = [f'<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="{H}" viewBox="0 0 1200 {H}"><rect width="1200" height="{H}" fill="#fff"/>',
     '<text x="40" y="60" font-size="38" font-weight="700" fill="#1a1a1a">Same four photos, two targets in the tool</text>',
     '<text x="40" y="104" font-size="28" fill="#555">Bytes of the JPEG it returned. Every result kept full size.</text>']
lx = X0 + 1_000_000 * SCALE
s.append(f'<line x1="{lx:.1f}" y1="150" x2="{lx:.1f}" y2="{H - 80}" stroke="#b42318" stroke-width="3" stroke-dasharray="10 8"/>')
s.append(f'<text x="{lx - 8:.1f}" y="186" font-size="28" font-weight="600" fill="#b42318" text-anchor="end">1,000,000 bytes</text>')
y = 230
for k in order:
    s.append(f'<text x="40" y="{y + 30}" font-size="28" font-weight="600" fill="#1a1a1a">{names[k]}</text>')
    s.append(f'<text x="40" y="{y + 70}" font-size="28" fill="#666">{rows[k]["t950"][1]} px</text>')
    for j, (key, col) in enumerate((("t950", "#2f5d8a"), ("t1mb", "#c4761b"))):
        b = rows[k][key][0]
        by = y + j * 50
        s.append(f'<rect x="{X0}" y="{by}" width="{b * SCALE:.1f}" height="40" rx="4" fill="{col}"/>')
        s.append(f'<text x="{X0 + b * SCALE - 14:.1f}" y="{by + 30}" font-size="28" font-weight="700" fill="#fff" text-anchor="end">{b:,}</text>')
    y += 150
s.append(f'<rect x="40" y="{H - 62}" width="28" height="28" fill="#2f5d8a"/><text x="80" y="{H - 38}" font-size="28" fill="#1a1a1a">typed 950 KB</text>')
s.append(f'<rect x="330" y="{H - 62}" width="28" height="28" fill="#c4761b"/><text x="370" y="{H - 38}" font-size="28" fill="#1a1a1a">the 1 MB button (1,048,576 bytes)</text>')
s.append("</svg>")
open(os.path.join(W, "fig/bytes-chart.html"), "w").write('<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;background:#fff;font-family:Inter,Helvetica,Arial,sans-serif}</style></head><body>' + "".join(s) + "</body></html>")
print("fig1", H, {k: rows[k] for k in order})

# Figure 2: centred 1:1, 4:5 and 4:3 crop boxes on the toy train photo (example ratios; Etsy publishes none).
crops = [json.loads(l) for l in open(os.path.join(W, "crop-all.jsonl")) if l.strip()]
tr = {c["ratio"]: c for c in crops if c["W"] == 3872 and c["H"] == 2592}
if set(tr) != {"1:1", "4:5", "4:3"}:
    sys.exit("crop-all.jsonl lacks the 3872 x 2592 rows")
PW, PH = 1120, round(1120 * 2592 / 3872)
jpg = os.path.join(W, "fig/train-bg.jpg")
subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", os.path.join(W, "photos/toy-train.jpg"), "-vf", f"scale={PW}:{PH}", "-q:v", "4", jpg], check=True)
b64 = base64.b64encode(open(jpg, "rb").read()).decode()
k = PW / 3872
TOP = 130
H2 = TOP + PH + 200
s = [f'<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="{H2}" viewBox="0 0 1200 {H2}"><rect width="1200" height="{H2}" fill="#fff"/>',
     '<text x="40" y="60" font-size="38" font-weight="700" fill="#1a1a1a">Where three thumbnail shapes overlap</text>',
     '<text x="40" y="104" font-size="28" fill="#555">Centred crops on a 3872 x 2592 photo. Ratios are examples.</text>',
     f'<image x="40" y="{TOP}" width="{PW}" height="{PH}" href="data:image/jpeg;base64,{b64}"/>']
cols = {"4:3": "#2f5d8a", "1:1": "#c4761b", "4:5": "#b42318"}
for r in ("4:3", "1:1", "4:5"):
    bw, bh = (int(v) for v in tr[r]["box"].replace("×", "x").split("x"))
    x = 40 + (3872 - bw) / 2 * k
    s.append(f'<rect x="{x:.1f}" y="{TOP + 3}" width="{bw * k:.1f}" height="{PH - 6}" fill="none" stroke="{cols[r]}" stroke-width="6"/>')
sw = int(tr["4:5"]["box"].replace("×", "x").split("x")[0])
sx = 40 + (3872 - sw) / 2 * k
s.append(f'<rect x="40" y="{TOP}" width="{sx - 40:.1f}" height="{PH}" fill="#fff" fill-opacity="0.55"/>')
s.append(f'<rect x="{sx + sw * k:.1f}" y="{TOP}" width="{sx - 40:.1f}" height="{PH}" fill="#fff" fill-opacity="0.55"/>')
ly = TOP + PH + 50
legend = [("4:3", f'4:3 box {tr["4:3"]["box"].replace("×", "x")}, keeps {tr["4:3"]["kept"]}'),
          ("1:1", f'1:1 box {tr["1:1"]["box"].replace("×", "x")}, keeps {tr["1:1"]["kept"]}'),
          ("4:5", f'4:5 box {tr["4:5"]["box"].replace("×", "x")}, keeps {tr["4:5"]["kept"]}: the safe zone')]
for i, (r, t) in enumerate(legend):
    s.append(f'<rect x="40" y="{ly + i * 56 - 26}" width="40" height="28" fill="none" stroke="{cols[r]}" stroke-width="6"/>')
    s.append(f'<text x="100" y="{ly + i * 56}" font-size="28" fill="#1a1a1a">{t}</text>')
s.append("</svg>")
open(os.path.join(W, "fig/crop-zones.html"), "w").write('<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;background:#fff;font-family:Inter,Helvetica,Arial,sans-serif}</style></head><body>' + "".join(s) + "</body></html>")
print("fig2", H2, tr)
