"""prompt_loader format-kwargs contract 회귀 테스트.

D6 T2 (commit 7891ed3) 가 turn_entity_detail.md 에 JSON literal `{"kind": ...}`
를 escape 없이 도입 → ``content.format(**kwargs)`` 가 placeholder 로 오인
``KeyError: '"kind"'`` 발생 → entity_t2i 전체 fail. 본 test 가 회귀 차단.

핵심 contract:
- ``load_prompt(module, name, **kwargs)`` 가 호출되면 ``str.format`` 적용.
  prompt 안의 JSON literal 은 ``{{`` / ``}}`` 로 escape 필수.
- ``load_prompt(module, name)`` (kwargs 없음) 은 format skip — escape 적용된
  prompt 를 LLM 에 보내면 LLM 이 literal ``{{`` 를 보게 됨 (잘못). 즉 kwargs
  없이 호출되는 prompt 는 escape 적용 금지.
"""
from __future__ import annotations

import pytest


# ---------------------------------------------------------------------------
# 1. turn_entity_detail — kwargs 경로 (entity_steps.py:740)
# ---------------------------------------------------------------------------


def test_turn_entity_detail_loads_with_kwargs_without_keyerror():
    """entity_t2i production path — KeyError 없이 로드."""
    from app.modules.prompt_loader import load_prompt
    out = load_prompt(
        "entity_extractor_v2", "turn_entity_detail",
        entity_name="테스트장소", entity_type="location",
    )
    # placeholder 정상 substitution
    assert "테스트장소" in out
    assert "(타입: location)" in out


def test_turn_entity_detail_preserves_single_brace_json_after_format():
    """LLM 에 보내는 결과는 single brace JSON — escape 가 unescape 됨.

    Area B (2026-05-13): metadata_json 이 closed shape {location, visual_identity}
    으로 확장 — character / outlook 은 `{"location": null, "visual_identity": null}`.
    """
    from app.modules.prompt_loader import load_prompt
    out = load_prompt(
        "entity_extractor_v2", "turn_entity_detail",
        entity_name="X", entity_type="location",
    )
    # JSON 예시는 single brace 로 LLM 에 도달해야 함
    assert '{"kind": "single_space"' in out
    assert '{"kind": "multi_space"' in out
    # Area B: character/outlook 의 closed-shape literal
    assert '{"location": null, "visual_identity": null}' in out


def test_turn_entity_detail_no_double_brace_residue_after_format():
    """format 후 결과에 ``{{`` literal 이 남으면 escape 가 잘못된 신호.

    Area B (2026-05-13): nested JSON 예시 (location.space_profile, prop.visual_identity)
    가 도입되어 OUTPUT 안에 nested object 의 legitimate `}}` (인접한 두 close-brace) 가
    존재 — escape 결함이 아니라 정상 JSON. 따라서 본 test 는 escape error 의 진짜
    신호인 ``{{`` (남은 open-brace escape) 만 가드.
    """
    from app.modules.prompt_loader import load_prompt
    out = load_prompt(
        "entity_extractor_v2", "turn_entity_detail",
        entity_name="X", entity_type="prop",
    )
    assert "{{" not in out


# ---------------------------------------------------------------------------
# 2. system — kwargs 없는 경로 (entity_extractor_v3.py:38)
# ---------------------------------------------------------------------------


def test_system_loads_without_kwargs_keeps_single_brace():
    """system prompt 는 kwargs 없이 로드 — format skip → 원본 brace 보존.

    `_load_system()` 가 kwargs 없이 호출되므로 prompt_loader.py:137 의 format
    skip 분기 진입. system.md 에 escape 적용하면 LLM 이 literal ``{{`` 를 보게
    되므로 escape 금지. 본 test 가 그 contract 를 가드.
    """
    from app.modules.prompt_loader import load_prompt
    out = load_prompt("entity_extractor_v2", "system")
    # system.md 의 D6 metadata_json 예시는 single brace 그대로 LLM 에 가야 함
    assert '"kind": "single_space"' in out
    # escape 적용되면 안 됨
    assert "{{" not in out
    assert "}}" not in out


# ---------------------------------------------------------------------------
# 3. 회귀 가드 — 미래 누군가가 entity_t2i kwargs 로드 깨면 잡음
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("etype", ["character", "location", "prop", "outlook"])
def test_turn_entity_detail_loads_for_all_entity_types(etype):
    """모든 entity_type 에 대해 KeyError 없이 로드 — _gen_t2i 의 4 path 커버."""
    from app.modules.prompt_loader import load_prompt
    out = load_prompt(
        "entity_extractor_v2", "turn_entity_detail",
        entity_name="dummy", entity_type=etype,
    )
    assert f"(타입: {etype})" in out
