"""bg_fill_tail 수리안 A/B 갤러리 — 조사 사진이 배경에 반영되는가.

A = 기록된 프롬프트 그대로 (「목록 밖 시설을 지어내지 마라」)
B = tail 617자만 교체 (시설과 외형을 가르고, 외형은 조사 사진 권위)

같은 참조·같은 샷·같은 나머지 프롬프트. ABBA 3회차.

★판정은 육안이다. 물음은 하나 — **그 지역 장소로 보이는가.**
  「달라졌다」가 아니라 「그 지역이 실제로 지니는 것(노면 표시·보도 마감·
  전주와 가공선·상점 얼굴과 간판)이 있는가」를 본다.

usage: build_bg_fabric_gallery.py
"""
import html
import json
import subprocess
from pathlib import Path

ROOT = Path("/Users/manta/Documents/Projects/TheRoad-I1")
OUT = ROOT / "artifact" / "20260825_bg_fabric_ab"
DRAFT = Path("/private/tmp/claude-501/-Users-manta-Documents-Projects-TheRoad-I1"
             "/e9fa4bb4-eeb7-49ef-819c-f7e09fc1224f/scratchpad/bg_fill_tail_v21_draft.md")
OLD = """THINGS THAT LIVE AT THIS PLACE (what they are, not where they go): the
list above names what permanently belongs to this site. Where each one
sits in this frame is decided by the attached sketch alone — do not add
or reposition anything on the strength of the list, build only what the
sketch already has lines for, and do not invent facilities that are not
listed."""


def lan_ip() -> str:
    try:
        return subprocess.run(["ipconfig", "getifaddr", "en0"],
                              capture_output=True, text=True, timeout=5).stdout.strip()
    except Exception:
        return "127.0.0.1"


def main() -> int:
    plan_f = OUT / "_plan.json"
    plan = json.loads(plan_f.read_text(encoding="utf-8")) if plan_f.exists() else []
    era = plan[0].get("era", "") if plan else ""
    refs = [Path(p).name for p in (plan[0].get("refs") or [])] if plan else []
    new_tail = DRAFT.read_text(encoding="utf-8").strip() if DRAFT.exists() else ""
    # 새 문단(둘째 덩어리)만 보여 준다 — 첫 문단은 원문과 거의 같다
    new_para = new_tail.split("\n\n")[1] if "\n\n" in new_tail else new_tail

    shots = sorted({p.name.split("_")[0] for p in OUT.glob("S*_[AB][0-9].png")})
    rows = []
    for sh in shots:
        cells = []
        for arm, label, note in (("A", "A — 현행", "「목록 밖 시설을 지어내지 마라」"),
                                 ("B", "B — 수리안", "시설과 외형을 가름")):
            imgs = sorted(OUT.glob(f"{sh}_{arm}[0-9].png"))
            for p in imgs:
                rnd = p.stem[-1]
                cells.append(
                    f'<figure><span class="tag t{arm}">{arm}{rnd}</span>'
                    f'<img loading="lazy" src="{p.name}" alt="{p.stem}">'
                    f'<figcaption>{label} · {rnd}회차<br>'
                    f'<span class="note">{note}</span></figcaption></figure>')
        rows.append(f'<section class="shot"><h2>{sh}</h2>'
                    f'<div class="grid">{"".join(cells)}</div></section>')

    doc = f"""<meta charset="utf-8">
<title>배경 외형 A/B — 조사 사진이 쓰이는가</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  :root {{ color-scheme: light dark; }}
  body {{ font: 15px/1.65 -apple-system, "Apple SD Gothic Neo", sans-serif;
         margin: 0; padding: 24px; background: #0f1115; color: #e6e8ee; }}
  h1 {{ font-size: 22px; margin: 0 0 4px; }}
  .lede {{ color: #a8b0c0; max-width: 80ch; margin: 0 0 20px; }}
  .lede b {{ color: #ffd479; }}
  .ask {{ background: #171a21; border-left: 3px solid #7fd1a0; padding: 12px 16px;
          border-radius: 0 8px 8px 0; margin: 0 0 22px; }}
  .diff {{ display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin: 0 0 26px; }}
  @media (max-width: 900px) {{ .diff {{ grid-template-columns: 1fr; }} }}
  .diff > div {{ background: #171a21; border-radius: 8px; padding: 12px 16px; }}
  .diff h3 {{ margin: 0 0 8px; font-size: 13px; color: #8f97a8; font-weight: 600; }}
  pre {{ white-space: pre-wrap; font: 12px/1.55 ui-monospace, monospace;
         margin: 0; color: #c3c9d6; }}
  .shot {{ margin: 0 0 34px; }}
  h2 {{ font-size: 17px; margin: 0 0 10px; }}
  .grid {{ display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }}
  @media (max-width: 1000px) {{ .grid {{ grid-template-columns: 1fr; }} }}
  figure {{ margin: 0; position: relative; }}
  figure img {{ width: 100%; border-radius: 6px; display: block; background: #000; }}
  .tag {{ position: absolute; top: 8px; left: 8px; z-index: 1; font-size: 12px;
          font-weight: 700; padding: 3px 9px; border-radius: 5px; }}
  .tA {{ background: #2b6cb0; color: #fff; }}
  .tB {{ background: #38795b; color: #fff; }}
  figcaption {{ font-size: 12px; color: #c3c9d6; padding: 6px 2px 0; }}
  .note {{ color: #8f97a8; }}
  .meta {{ font-size: 12px; color: #8f97a8; margin: 0 0 18px; }}
</style>
<h1>배경 외형 A/B — 조사한 사진이 실제로 쓰이는가</h1>
<p class="lede">
  검색·조사는 정상 작동해 <b>진짜 한국 사거리 사진</b>을 확보했고 프롬프트에
  <code>PERIOD REFERENCE</code> 로 붙습니다. 그런데 같은 프롬프트의 다른 절이
  <b>「목록 밖 시설은 지어내지 마라」</b>고 막고, 그 목록에는 시설 이름
  (<code>intersection / approach / streetlight / alley</code>)뿐이라
  전봇대·전선·점자블록·간판이 전부 「목록 밖」이 됩니다.
</p>
<div class="ask">
  <b>봐 주실 물음 하나</b> — 「달라졌는가」가 아니라
  <b>「그 지역 장소가 실제로 지니는 것이 화면에 있는가」</b>입니다.
  노면 표시 · 보도 마감 · 전주와 가공선 · 상점 얼굴과 간판 · 벽과 창 재질.
</div>
<div class="meta">
  조사 대상: {html.escape(era)} · 양쪽에 똑같이 붙인 참조: {html.escape(' · '.join(refs))}
  · 나머지 프롬프트 5,081자는 <b>바이트 동일</b>
</div>
<div class="diff">
  <div><h3>A — 현행 (걷어낸 617자)</h3><pre>{html.escape(OLD)}</pre></div>
  <div><h3>B — 수리안이 더한 문단</h3><pre>{html.escape(new_para)}</pre></div>
</div>
{''.join(rows)}
"""
    (OUT / "index.html").write_text(doc, encoding="utf-8")
    n = len(list(OUT.glob("S*_[AB][0-9].png")))
    print(f"이미지 {n}장 · 샷 {len(shots)}")
    print(f"→ http://{lan_ip()}:8940/artifact/20260825_bg_fabric_ab/")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
