"""장소 참조 3-arm 갤러리 — 조사한 「장소 전체」 사진을 붙이면 그 지역다워지는가.

    arm A  도로 표시 사진 + 현행 tail          (현행 그대로)
    arm C  ★장소 전경 사진 + 현행 tail         (참조 교체 효과만)
    arm B  ★장소 전경 사진 + v22 대응표 tail   (둘 다)

A→C 가 「참조를 바꾼 효과」, C→B 가 「그 조건에서 tail 을 바꾼 효과」다.

★판정은 육안이다. 물음 둘을 **나눠서** 본다 —
  ① 그 지역 장소가 실제로 지니는 것이 화면에 있는가 (노면 표시·보도 마감·
     전주와 가공선·상점 얼굴과 간판·벽과 창 재질)
  ② 참조에 **없던 것을 지어내지는** 않았는가 (새 건물·새 시설·읽을 수 있는
     가짜 상호). 라벨이 권위 범위를 정하므로, 그 범위 밖이면 전달이 아니라 발명이다.

usage: build_bg_place_ref_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_place_ref_ab"
RECIPE = (ROOT / "projects/da049582-2c6d-492c-979d-f468d61bab6e/images"
          "/fb7a883f-baac-4145-9131-732ce628d474/scene/recipe")

ARMS = [
    ("A", "현행", "도로 표시 사진 + 현행 tail", "#2b6cb0"),
    ("C", "참조만 교체", "★장소 전경 사진 + 현행 tail", "#7b5ea7"),
    ("B", "참조 + tail", "★장소 전경 사진 + 관할 대응표 tail", "#38795b"),
]


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"
    if f.exists():
        plan = json.loads(f.read_text(encoding="utf-8"))

    # 참조 사진 둘을 갤러리에도 건다 — 「무엇을 베끼라 했는가」를 같이 봐야 한다
    for name in ("eraref_ae2d4d155c10d3e3.png", "eraref_de840c9ca2c8d05b.png"):
        src = RECIPE / name
        if src.exists() and not (OUT / name).exists():
            (OUT / name).write_bytes(src.read_bytes())

    rounds = sorted({p.stem[-1] for p in OUT.glob("S2sh1_[ACB][0-9].png")})
    rows = []
    for r in rounds:
        cells = []
        for key, short, note, col in ARMS:
            p = OUT / f"S2sh1_{key}{r}.png"
            if not p.exists():
                cells.append('<figure class="miss"><div class="ph">없음</div></figure>')
                continue
            cells.append(
                f'<figure><span class="tag" style="background:{col}">{key} · {html.escape(short)}</span>'
                f'<img loading="lazy" src="{p.name}" alt="{p.stem}">'
                f'<figcaption>{html.escape(note)}</figcaption></figure>')
        rows.append(f'<section><h2>{r}회차</h2><div class="grid">{"".join(cells)}</div></section>')

    doc = f"""<meta charset="utf-8">
<title>장소 참조 3-arm — 조사한 사진이 그 지역을 만드는가</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; }}
  h2 {{ font-size: 15px; margin: 0 0 10px; color: #8f97a8; font-weight: 600; }}
  .lede {{ color: #a8b0c0; max-width: 82ch; margin: 0 0 18px; }}
  .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; max-width: 82ch; }}
  .ask ol {{ margin: 8px 0 0; padding-left: 20px; }}
  .refs {{ display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin: 0 0 28px; }}
  @media (max-width: 900px) {{ .refs {{ grid-template-columns: 1fr; }} }}
  .refs figure {{ margin: 0; }}
  .refs img {{ width: 100%; border-radius: 6px; display: block; }}
  .refs figcaption {{ font-size: 12px; color: #c3c9d6; padding: 6px 2px 0; }}
  section {{ margin: 0 0 30px; }}
  .grid {{ display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }}
  @media (max-width: 1100px) {{ .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; color: #fff;
          font-size: 12px; font-weight: 700; padding: 3px 9px; border-radius: 5px; }}
  figcaption {{ font-size: 12px; color: #8f97a8; padding: 6px 2px 0; }}
  .miss .ph {{ aspect-ratio: 16/9; display: grid; place-items: center;
               background: #171a21; border-radius: 6px; color: #565e6e; }}
</style>
<h1>장소 참조 3-arm — 조사한 사진이 그 지역을 만드는가</h1>
<p class="lede">
  era 조사는 <b>정답을 확보하고도 버렸습니다</b>. 「한국의 현대 골목길 사거리」로
  조사한 사진(아래 왼쪽)이 어디에도 안 쓰이고, 이 샷에는 「도로 노면 표시」
  사진(오른쪽)만 붙었습니다. <b>가장 좁은 것이 붙은 셈</b>입니다.
  <br>★역할문이 <code>It decides ONLY what <b>this thing</b> looks like</code> 이라
  <b>라벨이 권위 범위를 정합니다</b> — 그래서 C·B 는 사진과 함께 <b>역할문 subject 도</b>
  갈았습니다.
</p>
<div class="ask">
  <b>봐 주실 물음은 둘이고, 나눠서 봐야 합니다</b>
  <ol>
    <li><b>그 지역이 실제로 지니는 것이 있는가</b> — 노면 표시 · 보도 마감 ·
        전주와 가공선 · 상점 얼굴과 간판 · 벽과 창 재질</li>
    <li><b>참조에 없던 것을 지어내지는 않았는가</b> — 새 건물 · 새 시설 ·
        읽을 수 있는 가짜 상호. 권위 범위 밖이면 전달이 아니라 <b>발명</b>입니다</li>
  </ol>
</div>
<div class="refs">
  <figure><img src="eraref_ae2d4d155c10d3e3.png" alt="장소 전경 참조">
    <figcaption><b>C·B 가 받은 참조</b> — 「한국의 현대 골목길 사거리」
    (그동안 버려져 있던 것)</figcaption></figure>
  <figure><img src="eraref_de840c9ca2c8d05b.png" alt="도로 표시 참조">
    <figcaption><b>A 가 받은 참조 (현행)</b> — 「사거리 도로 노면 표시 및 횡단보도」
    </figcaption></figure>
</div>
{''.join(rows)}
"""
    (OUT / "index.html").write_text(doc, encoding="utf-8")
    n = len(list(OUT.glob("S2sh1_[ACB][0-9].png")))
    print(f"이미지 {n}장 · {len(rounds)}회차")
    print(f"→ http://{lan_ip()}:8940/artifact/20260825_bg_place_ref_ab/")
    return 0


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