"""컨트리로드 3판(새 프로젝트) 진행 갤러리 — 단계별 최근 이미지.

쓰기: .venv/bin/python build_cr3_gallery.py [stage ...]
     인자가 없으면 모든 stage 를 단계별로 묶어 보여준다.
"""
from __future__ import annotations

import html
import os
import subprocess
import sys
from datetime import datetime
from pathlib import Path

PROJ = "91b9626e-83ee-4a85-9208-0c8e2d153a63"
EPI = "e565764e-23fa-4991-a743-975fd8d061df"
PER_STAGE = 40
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "artifact" / f"{datetime.now():%Y%m%d}_컨트리로드3판_진행"


def q(sql: str) -> list[list[str]]:
    out = subprocess.run(
        ["psql", "-h", "localhost", "-U", "theroad", "-d", "theroad",
         "-t", "-A", "-F", "\x1f", "-c", sql],
        capture_output=True, text=True,
        env={"PGPASSWORD": "theroad_dev_2026",
             "PATH": "/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin"},
    )
    if out.returncode != 0:
        raise RuntimeError(out.stderr[:300])
    return [ln.split("\x1f") for ln in out.stdout.splitlines() if ln.strip()]


def main() -> None:
    want = sys.argv[1:]
    cond = ""
    if want:
        names = ", ".join("'" + s.replace("'", "''") + "'" for s in want)
        cond = f" AND stage IN ({names})"
    rows = q(
        "SELECT stage, file_path, coalesce(generation_model,''), "
        "coalesce(shot_index::text,''), coalesce(variant_label,''), "
        "coalesce(status,''), created_at "
        f"FROM image_asset WHERE episode_id='{EPI}'{cond} "
        "ORDER BY stage, created_at DESC;"
    )
    OUT.mkdir(parents=True, exist_ok=True)
    by_stage: dict[str, list] = {}
    for r in rows:
        by_stage.setdefault(r[0], []).append(r)

    parts = ['<meta charset="utf-8">',
             "<style>body{background:#111;color:#ddd;font-family:system-ui;"
             "margin:16px}h2{margin:28px 0 8px;color:#fff}"
             ".g{display:flex;flex-wrap:wrap;gap:10px}"
             ".c{width:300px}.c img{width:300px;border-radius:6px;"
             "background:#000}.m{font-size:11px;color:#9a9a9a;"
             "word-break:break-all}</style>",
             f"<h1>컨트리로드 3판 — {datetime.now():%m-%d %H:%M} KST</h1>"]
    total = 0
    for stage in sorted(by_stage):
        items = by_stage[stage][:PER_STAGE]
        parts.append(f"<h2>{html.escape(stage)} "
                     f"<small>({len(by_stage[stage])}장, 최근 {len(items)})"
                     f"</small></h2><div class='g'>")
        for st, fp, model, shot, vlab, status, made in items:
            total += 1
            src = fp if fp.startswith("http") else ("/" + fp.lstrip("/"))
            tag = " ".join(x for x in (f"sh{shot}" if shot else "",
                                       vlab, model, status) if x)
            parts.append(
                f"<div class='c'><img loading='lazy' src='{html.escape(src)}'>"
                f"<div class='m'>{html.escape(tag)}<br>"
                f"{html.escape(made[:19])}</div></div>")
        parts.append("</div>")
    (OUT / "index.html").write_text("\n".join(parts), encoding="utf-8")
    ip = subprocess.run(["ipconfig", "getifaddr", "en0"],
                        capture_output=True, text=True).stdout.strip()
    print(f"{total}장 · {OUT}/index.html")
    print(f"http://{ip}:8940/artifact/{OUT.name}/")


if __name__ == "__main__":
    main()
