#!/usr/bin/env python3
"""임시 — bg2_S4sh1 VLM 이중 분석 → 결함 취합 → i2i 수정.

판정 축(범용): ①프롬프트 충실 ②물리 정합 ③첨부 마스터와의 구조 일치
(매싱·층수·계단·옥탑·마당) ④프롬프트가 선언한 지역·시대의 실물 사실성
(그 지역 실제 건물·거리로 보여야 함 — 외국풍/무국적 배제).
산출: bg2fix_S4sh1.png
"""
import sys
from pathlib import Path

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

TAG = "S4sh1"
MASTER = HERE / "out" / "forest_map" / "top2" / "top2_photo_fixed_nb2.png"
CAND = L.OUT / f"bg2_{TAG}.png"
OUTF = L.OUT / f"bg2fix_{TAG}.png"

p37 = F.load_plan(W.PLAN)
bg_prompt = p37["ext_bg"][TAG]["bg_prompt_en"]

CRITIQUE_SYS = "\n".join([
    "You are given: an image-generation prompt, a MASTER location",
    "photograph (the ground-truth look of this property), and ONE",
    "candidate photograph generated from the prompt with the master",
    "attached as reference. List what is WRONG with the candidate:",
    "- fidelity: any visible deviation from the prompt's stated",
    "  structure, camera, materials, state and exclusions,",
    "- physical coherence: any construction that could not physically",
    "  work (floating or split volumes, stairs that do not reach their",
    "  destination, impossible geometry),",
    "- MASTER consistency: any structural mismatch with the master",
    "  photograph — number of storeys, massing, the external stair's",
    "  full run, the rooftop structure's placement, walls, gate and",
    "  yard layout must match the master,",
    "- regional authenticity: the prompt declares a real region and",
    "  era; every building, street and object must look like the",
    "  real, ordinary built environment of that region — flag anything",
    "  that reads foreign, genericized or theme-park-like.",
    "Base every finding only on what is visible. Ignore taste.",
    "issues: each finding as issue_ko (one short Korean line) plus",
    "fix_en (ONE imperative English edit instruction fixing exactly",
    "that finding while changing nothing else). Empty array if nothing",
    "is wrong.",
])

parts = [
    {"type": "text", "text": "THE PROMPT:\n" + bg_prompt},
    {"type": "text", "text": "MASTER photograph (ground truth):"},
    F.png_data_url(MASTER),
    {"type": "text", "text": "Candidate photograph to examine:"},
    F.png_data_url(CAND),
]
critique = {}
for model, tag in (("gpt", "x_bgfix_s4_gpt"),
                   ("gemini-pro", "x_bgfix_s4_gemini")):
    critique[model] = F.llm(tag, CRITIQUE_SYS, parts, T.CRITIQUE_SCHEMA,
                            model=model)
    print(f"critique[{model}]: {len(critique[model]['issues'])}건")
    for i in critique[model]["issues"]:
        print("  -", i["issue_ko"])

fix_lines = [f"- ({title}) {i['fix_en']}"
             for model, title in (("gpt", "GPT VLM"),
                                  ("gemini-pro", "Gemini VLM"))
             for i in critique[model]["issues"]]
if not fix_lines:
    print("결함 0 — 수정 불필요")
    sys.exit(0)

fix_prompt = "\n\n".join([
    T.FIX_HEAD,
    "ISSUES TO FIX:\n" + "\n".join(fix_lines),
    "The attached MASTER photograph is the ground truth for the"
    " property's structure — align every fixed feature to it.",
    T.PRESERVE_TAIL,
])
F.img_nb2("x_bgfix_s4_fix", fix_prompt,
          [(T.FIX_LABEL, CAND),
           ("MASTER photograph — ground truth of this property's"
            " structure; align the edited photo's building to it.",
            MASTER)],
          aspect_ratio="16:9", out_path=OUTF)
print("saved:", OUTF)
