"""Wave1 회귀 — shot_extract user 프롬프트 str.format() KeyError 크래시 fix.

금월도 E2E 에서 shot_extract step 이
``KeyError: 'possession, transformation, ghost, projection, superpower, body_deformation'``
로 크래시했다. 원인 = shot_extract v14 user.md 의 rule_type enum 설명 줄이 raw
중괄호를 포함 → ``beat_shot_steps.py`` 의 ``user_template.format()`` 가 그것을
치환 필드로 해석. v15 에서 이중 중괄호로 escape (``.format()`` 후 렌더 결과는
v14 의도와 동일).
"""
from pathlib import Path

from app.modules.prompt_loader import load_prompt

_REPO_ROOT = Path(__file__).resolve().parents[3]
_V15_USER = _REPO_ROOT / "prompts/_base/shot_extract/15.202605201546/user.md"

# rule_type enum 설명 — 렌더 후 보여야 할 literal 형태.
_RULE_TYPE_ENUM_LITERAL = (
    "{possession, transformation, ghost, projection, superpower, body_deformation}"
)


def _production_format(user_template: str) -> str:
    """beat_shot_steps.py:481 production ``.format()`` 호출 재현."""
    return user_template.format(
        ref_section="<REF_SECTION>",
        scenes_section="<SCENES_SECTION>",
        character_list_section="<CHARACTER_LIST_SECTION>",
    )


def test_g1_shot_extract_user_format_no_keyerror():
    """active shot_extract user 프롬프트가 production ``.format()`` 에서 KeyError 안 냄.

    pre-fix(v14 raw 중괄호): ``KeyError`` raise. post-fix(v15 escape): 정상 렌더.
    """
    user_template = load_prompt("shot_extract", "user")
    rendered = _production_format(user_template)  # pre-fix 면 여기서 KeyError
    assert "<REF_SECTION>" in rendered
    assert "<SCENES_SECTION>" in rendered
    assert "<CHARACTER_LIST_SECTION>" in rendered


def test_g2_rule_type_enum_literal_preserved():
    """escape 후 렌더 결과에 rule_type enum 목록이 literal 중괄호로 보존됨."""
    user_template = load_prompt("shot_extract", "user")
    rendered = _production_format(user_template)
    assert _RULE_TYPE_ENUM_LITERAL in rendered


def test_g3_v15_source_escaped_braces():
    """v15 user.md 소스가 이중 중괄호 escape 형태를 포함 (active fix 핀)."""
    src = _V15_USER.read_text(encoding="utf-8")
    escaped = (
        "{{possession, transformation, ghost, projection, superpower, "
        "body_deformation}}"
    )
    assert escaped in src
