"""프롬프트가 말하는 첨부와 **실제 붙는 참조**가 어긋나지 않는다 (2026-08-27).

감사 P0-A. 종전에는 `loc_tail` 갈래가 넷뿐이라 나머지가 전부
「the attached LOCATION PHOTOGRAPH shows the exact spot.」로 떨어졌다.
그 문장이 참이려면 `build_still_refs` 가 `plate_label`(= "LOCATION
PHOTOGRAPH — …")을 붙여야 하는데, 붙는 조건은
`plate is not None and prev_sel is None` 하나다.

실측(records.json 전수): SHOT BACKGROUND 만 참조하면서 프롬프트는
LOCATION PHOTO 라고 한 후보 482개(233 채택), location-photo 계열 참조가
아예 없는 샷 110개(109 채택).

★**조립부만 재지 않는다.** 프롬프트와 참조 라벨을 **같이** 만들어,
 「프롬프트가 있다고 말한 것」이 「참조 라벨에 실제로 있는지」를 잰다.
"""
from pathlib import Path

from app.modules.pipeline.still_recipe import (
    build_bgfirst_refs,
    build_still_prompt,
    build_still_refs,
)

_PHOTO_CLAIM = "the attached LOCATION PHOTOGRAPH"
_LOC_LABEL = "LOCATION PHOTOGRAPH"


def _prompt(**kw) -> str:
    base = dict(
        shot_desc="민수가 자전거 체인에 손을 댄다.",
        place_text="Inside a narrow bicycle repair shop.",
        time_of_day_en="evening",
        world_anchor="present-day Seoul",
        bg_only=False,
        prev_used=False,
        prev_usage_en="",
        pose_clauses="",
        movement_en="",
        figures_en="",
        carried_en="",
        char_names=[],
        prompt_version="1",
    )
    base.update(kw)
    return build_still_prompt(**base)


def _labels(refs) -> str:
    return "\n".join(lbl for lbl, _ in refs)


def test_plate_attached_prompt_and_refs_agree(tmp_path):
    """① 배경 사진이 붙는 갈래 — 프롬프트도 참조도 LOCATION PHOTOGRAPH."""
    plate = tmp_path / "plate.png"
    plate.write_bytes(b"x")
    refs = build_still_refs(
        bg_only=False, plate=plate, conti=None, prev_sel=None,
        char_refs=[], prop_refs=[], prompt_version="1",
    )
    prompt = _prompt(plate_attached=True)
    assert _PHOTO_CLAIM in prompt
    assert _LOC_LABEL in _labels(refs), "참조에 LOCATION PHOTOGRAPH 가 없다"


def test_text_only_prompt_does_not_claim_a_photo():
    """② 참조가 아예 없는 갈래 — 프롬프트가 첨부를 주장하면 안 된다."""
    refs = build_still_refs(
        bg_only=False, plate=None, conti=None, prev_sel=None,
        char_refs=[], prop_refs=[], prompt_version="1",
    )
    prompt = _prompt(plate_attached=False)
    assert _LOC_LABEL not in _labels(refs)
    assert _PHOTO_CLAIM not in prompt, (
        "참조가 0인데 프롬프트가 LOCATION PHOTOGRAPH 를 가리킨다")
    assert "no location photograph is attached" in prompt


def test_bgfirst_step2_prompt_does_not_claim_a_location_photo(tmp_path):
    """③ bgfirst Step2 — 참조는 SHOT BACKGROUND 인데 프롬프트가 뭐라 하나.

    `build_bgfirst_refs` 는 갈래와 무관하게 [SHOT BACKGROUND, (LAYOUT),
    엔티티] 만 붙인다. 그러니 Step2 프롬프트는 chain_bg 갈래여야 한다.
    """
    bg = tmp_path / "bg.png"
    bg.write_bytes(b"x")
    refs = build_bgfirst_refs(
        bg=bg, conti=None, char_refs=[], prop_refs=[],
    )
    labels = _labels(refs)
    assert _LOC_LABEL not in labels, "bgfirst Step2 에 location photo 가 있다"
    assert "SHOT BACKGROUND" in labels

    prompt = build_still_prompt(
        shot_desc="민수가 자전거 체인에 손을 댄다.",
        place_text="Inside a narrow bicycle repair shop.",
        time_of_day_en="evening", world_anchor="present-day Seoul",
        bg_only=False, prev_used=False, prev_usage_en="", pose_clauses="",
        movement_en="", figures_en="", carried_en="", char_names=[],
        chain_bg_mode=True, prompt_version="1",
    )
    assert _PHOTO_CLAIM not in prompt
    assert "SHOT BACKGROUND" in prompt


def test_the_check_would_catch_the_old_behaviour():
    """양성 — 옛 기본값(plate_attached=True)이면 참조 0에도 사진을 주장한다.

    이 테스트가 초록이라는 것은 위 ②가 **진짜로 갈래를 갈랐다**는 뜻이다.
    기본값을 안 바꿨으니 옛 동작은 그대로 재현된다(byte-identical 보장).
    """
    refs = build_still_refs(
        bg_only=False, plate=None, conti=None, prev_sel=None,
        char_refs=[], prop_refs=[], prompt_version="1",
    )
    assert _LOC_LABEL not in _labels(refs)
    assert _PHOTO_CLAIM in _prompt(), (
        "기본값이 옛 동작을 재현하지 않는다 — 다른 곳이 바뀌었다")
