#!/usr/bin/env python3
"""임시 실험 — S12sh11/18/21 + S14sh5 를 한 장(2x2 4분할) 실사로 생성.

참조 = 각 샷의 s37 스케치(콘티) 패널 4장 + 실내 배경 플레이트 1장만
(캐릭터·prev 없음 — 사용자 지정). 자세 정본·carried state 는 텍스트 주입.
가설: 한 생성 안의 패널들 = 장소·시신 자세 내적 일관(s34 콘티 지식의
실사판) 검증.
"""
import sys
from pathlib import Path

HERE = Path(__file__).parent
sys.path.insert(0, str(HERE))
import forest_lib as F  # noqa: E402
import s35_fullrun as R  # noqa: E402
import s37_rooftop_rebuild as W  # noqa: E402
import s34_stillrun as S  # noqa: E402

TAGS = ["S12sh11", "S12sh18", "S12sh21", "S14sh5"]
OUTF = W.OUT / "quad_s12.png"

plan = F.load_plan(W.PLAN)
plan35 = W._s35()
mv = W._movement(plan35)
gmap = {g["key"]: g for g in plan35["groups"]}
place_en = gmap[W.INT_GROUP]["place_en"]

# 참조: 콘티 패널 4장(패널 순서) + 배경 플레이트(중복 제거)
tag2plate = {}
for p_ in plan["int_plates"]:
    for t in p_["covers"]:
        tag2plate[t] = W.OUT / f"plate_{p_['key']}.png"
refs = []
for i, tag in enumerate(TAGS, 1):
    refs.append((f"STORYBOARD PANEL for PANEL {i} — a REFERENCE ONLY,"
                 " never the target: use it loosely for that panel's"
                 " camera framing, figure placement and depth order;"
                 " never copy its sketch style.",
                 W.OUTP / f"{tag}.png"))
plates = []
for tag in TAGS:
    p = tag2plate[tag]
    if p not in plates:
        plates.append(p)
for p in plates:
    refs.append((W.PLATE_STILL_LABEL, p))

# 패널 텍스트: 샷 텍스트+동선/크기(pose_fix 우선)+carried+시간
lines = []
for i, tag in enumerate(TAGS, 1):
    s = R.SHOT[R._key(tag)]
    m = mv.get(tag, {})
    fix = plan.get("pose_fix", {}).get(tag) or {}
    movement = fix.get("movement_en") or m.get("movement", "")
    figures = fix.get("figures_en") or m.get("figures", "")
    carried = fix.get("carried_en") or (plan.get("int_cont", {})
                                        .get(tag, {}).get("carried_en", ""))
    line = (f"PANEL {i} ({tag}) — TIME OF DAY (lock): {S._time_of(tag)}."
            f"\n  SHOT TEXT (authoritative, Korean): {S._soften(s['desc'])}")
    if movement:
        line += f"\n  MOVEMENT (follow exactly): {S._soften(movement)}"
    if figures:
        line += ("\n  FIGURES — size & depth (follow exactly): "
                 + S._soften(figures))
    if carried:
        line += ("\n  CARRIED STATE (persist exactly across panels): "
                 + S._soften(carried))
    line += f"\n  Composition reference: STORYBOARD PANEL for PANEL {i}."
    lines.append(line)

pose_clauses = []
for it in plan.get("pose_canon", []):
    if any(t in it["shots"] for t in TAGS):
        pose_clauses.append(
            "IMMOBILE CHARACTER POSE — CANONICAL (identical wherever this"
            " character appears in ANY panel; on any conflict THIS POSE"
            " WINS): " + S._soften(it["pose_en"]))

prompt = "\n\n".join([
    "Create ONE image split into 4 photorealistic live-action film"
    " stills: 4 panels made by ONE vertical cut at exactly 50% of the"
    " width and ONE horizontal cut at exactly 50% of the height — a 2x2"
    " grid, each panel exactly one quarter of the image, separated only"
    " by thin straight black gutter lines at those exact positions."
    " Panels are numbered 1 (top-left), 2 (top-right), 3 (bottom-left),"
    " 4 (bottom-right). Every panel is a FINAL photorealistic film"
    " still — contemporary South Korea, 2026; all people are Korean"
    " unless stated.",
    f"LOCATION (lock, same interior in all panels): {place_en} The"
    " attached LOCATION PHOTOGRAPH shows the exact place.",
    "PANELS ARE CHRONOLOGICAL — CONTINUE THE ACTION: each panel starts"
    " from the previous panel's end state (each person's position, pose,"
    " held objects, and the state of the room), advancing only what its"
    " shot text says. The SAME single location, its materials, fixed"
    " features and wear are identical across panels.",
    "\n".join(pose_clauses) if pose_clauses else "",
    S.REALIZE_STILL,
    "PANELS (one shot per panel):",
    "\n".join(lines),
    "No text, captions, watermarks or annotations anywhere in any"
    " panel.",
])

F.img_nb2("x_quad_s12", prompt, refs, aspect_ratio="1:1", out_path=OUTF)
print("saved:", OUTF)
print()
print(prompt)
