#!/usr/bin/env python3
"""마스터 v2 — 프롬프트 재작성 후 s29 체인 재실행.

진단(사용자 확정): 구 프롬프트는 ①도면 언어 이식 ②본 건물에 국적 앵커
없음(Korean 은 주변 동네에만)+villa 오용 ③외관·생활감 서술 전무
④'filming property' 프레이밍 → 공장 같은 무국적 박스.

체인: ①LLM 재작성(배치·스케일 사실 보존) → ②nb2 3롤(참조 0) →
③GPT/Gemini 합산 판정 → ④결함 취합 i2i 수정 = out/s38/master2.png
"""
import shutil
import sys
from pathlib import Path

HERE = Path(__file__).parent
sys.path.insert(0, str(HERE))
import forest_lib as F  # noqa: E402
import s38_lightconti_full as L  # noqa: E402
import s29_top_v2 as T  # noqa: E402

OLD = F.load_plan("top2_place_v1")["photo_prompt_en"]
LABELS = ["A", "B", "C"]

REWRITE_SYS = "\n".join([
    "당신은 T2I 프롬프트 편집자다. 입력된 이미지 생성 프롬프트를 아래",
    "계약대로 재작성하라. 입력의 모든 공간 배치·연결 관계·스케일 사실",
    "(골목-대문-마당-계단-옥상-옥탑방 동선, 3층, 철제 후설치 계단,",
    "옥상 물탱크·빨래줄·건조 평상, 창 구성 등)은 하나도 빠짐없이",
    "보존하되 표현만 바꾼다.",
    "1) 도면·스케치 언어 전면 제거: draw/sketch/mark/detail sketch 류를",
    "   전부 '실제 사진에 무엇이 보이는가' 서술로 재작성.",
    "2) 본 건물의 국적·성격 명시: 'an ordinary lived-in South Korean",
    "   low-rise multi-family house on a real residential street,",
    "   contemporary South Korea, 2026'. 단어 villa 는 쓰지 마라.",
    "   'filming property' 표현도 금지.",
    "3) FACADE & LIVED-IN 절 신설: 그 지역·시대의 실물 전형을 따르라고",
    "   위임하는 서술 — 실제 한국 다세대 주택에서 흔히 보이는 외장",
    "   마감·창호와 방범창·에어컨 실외기·가스 배관·옥상 방수면·난간·",
    "   우편함·계량기·화분 같은 생활 흔적이 층층이 보이는, 사람이",
    "   실제로 사는 집. 특정 색상·자재를 단정하지 말고 '그 지역 실물",
    "   전형'에 맡겨라.",
    "4) 유지: 45도 고공 카메라로 마당 너머 건물을 보며 부지 전체가 한",
    "   프레임, 참조 이미지 없음 선언, 중립 주간광, 사람 없음, 읽히는",
    "   텍스트·간판 없음, 특정 사건의 순간 상태물 없음, 주석·마커류",
    "   금지, 주변=한국 저층 밀집 주거지 실물.",
    "출력: master_prompt_en (완결된 영어 프롬프트 전문).",
])
SCHEMA = {"type": "object", "additionalProperties": False,
          "properties": {"master_prompt_en": {"type": "string"}},
          "required": ["master_prompt_en"]}
res = F.llm("x_master2_rewrite", REWRITE_SYS,
            "재작성할 프롬프트 전문:\n\n" + OLD, SCHEMA)
prompt = res["master_prompt_en"]
plan = F.load_plan(L.PLAN)
plan["master2"] = {"prompt": prompt}
F.save_plan(L.PLAN, plan)
print("=== 재작성 프롬프트 ===")
print(prompt)

cands = []
for lab in LABELS:
    out = L.OUT / f"master2_{lab.lower()}.png"
    F.img_nb2(f"x_master2_{lab.lower()}", prompt, [],
              aspect_ratio="1:1", out_path=out)
    cands.append(out)
parts = [{"type": "text",
          "text": "THE PROMPT (all three candidates were generated"
                  " from this):\n" + prompt}]
for lab, p in zip(LABELS, cands):
    parts.append({"type": "text", "text": f"Candidate {lab}:"})
    parts.append(F.png_data_url(p))
judge = {}
for model, mtag in (("gpt", "x_master2_judge_gpt"),
                    ("gemini-pro", "x_master2_judge_gem")):
    judge[model] = F.llm(mtag, T.JUDGE_SYSTEM, parts, T.JUDGE_SCHEMA,
                         model=model)
totals = {lab: sum(
    next(v["score"] for v in judge[m]["verdicts"] if v["label"] == lab)
    for m in ("gpt", "gemini-pro")) for lab in LABELS}
best = max(totals.values())
tied = [lab for lab, t in totals.items() if t == best]
gem_rank = judge["gemini-pro"]["ranking"]
sel = min(tied, key=lambda lab: gem_rank.index(lab)
          if lab in gem_rank else 99)
sel_path = L.OUT / f"master2_{sel.lower()}.png"
print(f"judge totals={totals} sel={sel}")

parts2 = [{"type": "text",
           "text": "THE PROMPT (the photograph was generated from"
                   " this):\n" + prompt},
          {"type": "text", "text": "Photograph to examine:"},
          F.png_data_url(sel_path)]
critique = {}
for model, mtag in (("gpt", "x_master2_crit_gpt"),
                    ("gemini-pro", "x_master2_crit_gem")):
    critique[model] = F.llm(mtag, T.CRITIQUE_SYSTEM, parts2,
                            T.CRITIQUE_SCHEMA, model=model)
    for i in critique[model]["issues"]:
        print(f"  [{model}] {i['issue_ko']}")
fix_lines = [f"- ({t2}) {i['fix_en']}"
             for model, t2 in (("gpt", "GPT VLM"),
                               ("gemini-pro", "Gemini VLM"))
             for i in critique[model]["issues"]]
final = L.OUT / "master2.png"
if final.exists():
    final.unlink()
if not fix_lines:
    shutil.copy(sel_path, final)
    print("결함 0 — 승자 그대로")
else:
    fp = "\n\n".join([T.FIX_HEAD,
                      "ISSUES TO FIX:\n" + "\n".join(fix_lines),
                      T.PRESERVE_TAIL])
    F.img_nb2("x_master2_fix", fp, [(T.FIX_LABEL, sel_path)],
              aspect_ratio="1:1", out_path=final)
    print(f"결함 {len(fix_lines)}건 수정 완료")
plan = F.load_plan(L.PLAN)
plan["master2"].update({"totals": totals, "selected": sel,
                        "critique": {m: critique[m]["issues"]
                                     for m in critique}})
F.save_plan(L.PLAN, plan)
print("saved:", final)
