#!/usr/bin/env python3
"""Side-by-side comparison: the mockup, the standalone agent's page, and mine."""
import glob
import os
import shutil

import numpy as np
from PIL import Image

SA = "/home/ubuntu/standalone"
MINE = "/home/ubuntu/skilltest/builds"
OUT = os.path.join(SA, "cmp")
os.makedirs(OUT, exist_ok=True)


def best_render(d):
    m = np.asarray(Image.open(f"{d}/mock.jpg").convert("RGB"), dtype=float)
    best = None
    for f in sorted(glob.glob(f"{d}/shots/it*.png")):
        if any(k in f for k in ("compare", "edges", "stack")):
            continue
        r = np.asarray(Image.open(f).convert("RGB"), dtype=float)
        if r.shape != m.shape:
            continue
        v = float(np.abs(m - r).mean())
        if best is None or v < best[0]:
            best = (v, f)
    return best


rows = []
for d in sorted(glob.glob(f"{SA}/builds/*")):
    slug = os.path.basename(d)
    b = best_render(d)
    if not b:
        continue
    mae_sa, render = b
    mine = f"{MINE}/{slug}/shots/final.png"
    mae_mine = None
    if os.path.exists(mine):
        m = np.asarray(Image.open(f"{d}/mock.jpg").convert("RGB"), dtype=float)
        r = np.asarray(Image.open(mine).convert("RGB"), dtype=float)
        if r.shape == m.shape:
            mae_mine = float(np.abs(m - r).mean())
        else:
            mine = None
    else:
        mine = None

    mock = Image.open(f"{d}/mock.jpg").convert("RGB")
    sa_img = Image.open(render).convert("RGB")
    mock.save(f"{OUT}/{slug}-mock.png")
    sa_img.save(f"{OUT}/{slug}-sa.png")
    if mine:
        Image.open(mine).convert("RGB").save(f"{OUT}/{slug}-mine.png")
    diff = np.abs(np.asarray(mock, dtype=float) - np.asarray(sa_img, dtype=float)).mean(2)
    Image.fromarray(np.clip(diff * 3, 0, 255).astype("uint8")).save(f"{OUT}/{slug}-diff.png")
    rows.append((slug, mae_sa, mae_mine, bool(mine)))

rows.sort(key=lambda r: r[1])
cards = []
for slug, sa, mine, has_mine in rows:
    delta = ""
    if mine is not None:
        d = mine - sa
        delta = f'<span class="d {"good" if d > 0 else "bad"}">{d:+.2f} vs mine</span>'
    mine_html = (
        f'<figure><img src="cmp/{slug}-mine.png" loading="lazy"><figcaption>mine'
        f' <b>{mine:.2f}</b></figcaption></figure>' if has_mine else
        '<figure class="none"><div>not built</div><figcaption>mine</figcaption></figure>')
    cards.append(f"""
  <article>
    <header><h2>{slug}</h2>
      <span class="sa">standalone <b>{sa:.2f}</b></span>{delta}</header>
    <div class="row">
      <figure><img src="cmp/{slug}-mock.png" loading="lazy"><figcaption>mockup</figcaption></figure>
      <figure><img src="cmp/{slug}-sa.png" loading="lazy"><figcaption>standalone agent <b>{sa:.2f}</b></figcaption></figure>
      {mine_html}
    </div>
    <details><summary>diff (standalone vs mock)</summary>
      <img class="diff" src="cmp/{slug}-diff.png" loading="lazy"></details>
  </article>""")

mean_sa = sum(r[1] for r in rows) / len(rows) if rows else 0
with_mine = [r for r in rows if r[2] is not None]
mean_mine = sum(r[2] for r in with_mine) / len(with_mine) if with_mine else 0

html = f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
<title>Standalone agent vs mine</title>
<style>
 body{{margin:0;background:#0e1116;color:#e8eaed;font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}}
 .wrap{{max-width:1500px;margin:0 auto;padding:32px 24px 80px}}
 h1{{font-size:26px;margin:0 0 6px}}
 .lede{{color:#9aa4b2;margin:0 0 28px;max-width:70ch}}
 .lede b{{color:#e8eaed}}
 article{{background:#161b22;border:1px solid #232a34;border-radius:10px;padding:16px 18px;margin:0 0 18px}}
 article header{{display:flex;align-items:baseline;gap:14px;margin:0 0 12px;flex-wrap:wrap}}
 h2{{font-size:16px;margin:0;font-weight:600;letter-spacing:.01em}}
 .sa{{color:#7ee787;font-size:13px}} .sa b{{font-size:15px}}
 .d{{font-size:12.5px;padding:2px 8px;border-radius:20px;background:#1f2937}}
 .d.good{{color:#7ee787}} .d.bad{{color:#f0883e}}
 .row{{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}}
 figure{{margin:0}}
 figure img{{width:100%;display:block;border-radius:5px;border:1px solid #232a34}}
 figcaption{{font-size:12px;color:#9aa4b2;margin-top:6px}}
 figcaption b{{color:#e8eaed}}
 .none div{{aspect-ratio:16/9;display:grid;place-items:center;border:1px dashed #30363d;border-radius:5px;color:#586069;font-size:13px}}
 details{{margin-top:12px}} summary{{cursor:pointer;color:#9aa4b2;font-size:13px}}
 .diff{{width:100%;margin-top:8px;border-radius:5px}}
 .totals{{display:flex;gap:28px;margin:0 0 26px;font-size:14px;color:#9aa4b2;flex-wrap:wrap}}
 .totals b{{color:#e8eaed;font-size:19px;display:block}}
</style></head><body><div class="wrap">
<h1>Standalone agent vs my builds</h1>
<p class="lede">Each row: the <b>mockup</b>, the page built by a <b>fresh agent given only SKILL.md
and the tools</b> (no conversation history), and the page I built with full context. Lower MAE is
closer to the mockup. Sorted best-first by standalone score.</p>
<div class="totals">
  <div><b>{mean_sa:.2f}</b>standalone mean ({len(rows)} built)</div>
  <div><b>{mean_mine:.2f}</b>my mean (same {len(with_mine)})</div>
</div>
{''.join(cards)}
</div></body></html>"""
open(os.path.join(SA, "compare.html"), "w").write(html)
print(f"wrote compare.html: {len(rows)} builds, standalone mean {mean_sa:.2f}, mine {mean_mine:.2f}")
