#!/usr/bin/env python3
"""임시 실험 3 — 4분할 체인을 참조 0(프롬프트만)으로 재실행.

사용자 진단: 콘티 스케치 참조가 최종 질감을 스케치/일러스트로 오염.
동일 과정: ①nb2 4분할 한 장(참조 없음, 텍스트 계약만) → ②등분 크롭 →
③패널별 '사실화만 극대화' i2i → quad2_refined_*.png 4장.
"""
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
import x_quad_refine as REFINE  # noqa: E402 — 사실화 프롬프트 재사용

TAGS = ["S12sh11", "S12sh18", "S12sh21", "S14sh5"]
OUTF = W.OUT / "quad2_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"]

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))
    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, as if captured on a real cinema camera on a real physical"
    " set — contemporary South Korea, 2026; all people are Korean"
    " unless stated. No reference image is attached — build everything"
    " from this text alone, in a single consistent photographic look.",
    f"LOCATION (lock, same interior in all panels): {place_en}",
    "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_quad2_s12", prompt, [], aspect_ratio="1:1", out_path=OUTF)
print("saved:", OUTF)

# ② 등분 크롭 → ③ 사실화 i2i (x_quad_refine 계약 재사용)
from PIL import Image  # noqa: E402
im = Image.open(OUTF).convert("RGB")
WIDTH, HEIGHT = im.size
boxes = [(0, 0, WIDTH // 2, HEIGHT // 2),
         (WIDTH // 2, 0, WIDTH, HEIGHT // 2),
         (0, HEIGHT // 2, WIDTH // 2, HEIGHT),
         (WIDTH // 2, HEIGHT // 2, WIDTH, HEIGHT)]
for tag, box in zip(TAGS, boxes):
    p = W.OUT / f"quad2_panel_{tag}.png"
    im.crop((box[0] + 4, box[1] + 4, box[2] - 4, box[3] - 4)).save(p)
    out = W.OUT / f"quad2_refined_{tag}.png"
    F.img_nb2(f"x_quad2_refine_{tag}", REFINE.PROMPT,
              [(REFINE.REF_LABEL, p)], aspect_ratio="1:1", out_path=out)
    print("refined:", out.name)
print("DONE")
