"""G4.6 Pre-Wave hotfix canary — RC-D label routing.

D2 fixture (S1_Shot5 location_ref, ref_usage='exact_background') 의 dependency
label 이 character ref 분기로 새지 않고 BACKGROUND (SAME ROOM) 분기로 dispatch
되는지 fixture-only smoke 검증. LLM 호출 없음.

실패 시 exit 1 + stderr 로그. 통과 시 stdout "OK".
"""
from __future__ import annotations

import json
import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[2]
BACKEND = REPO_ROOT / "backend"
sys.path.insert(0, str(BACKEND))

from app.services.prompt_service import resolve_ref_roles  # noqa: E402

FIXTURE = REPO_ROOT / "backend" / "tests" / "fixtures" / "g4_6" / "s1_shot5_dependency.json"


def build_exact_background_label(fixture_path: Path) -> str:
    """`scene_reference_service.py:690-698` 의 exact_background label 조립
    로직을 재현 — fixture 의 ref_usage / ignore_elements / keep_elements 사용.
    """
    dep = json.loads(fixture_path.read_text())["dependency"]
    refs = dep.get("location_refs") or []
    if not refs:
        raise RuntimeError(f"fixture {fixture_path} location_refs empty")
    ref = refs[0]
    if ref.get("ref_usage") != "exact_background":
        raise RuntimeError(
            f"fixture ref_usage='{ref.get('ref_usage')}' (exact_background expected) — D2 회귀 패턴 아님"
        )
    label = "previous shot at same location (SAME ROOM) — use this background as-is."
    if ref.get("ignore_elements"):
        label += f" {ref['ignore_elements']}"
    if ref.get("keep_elements"):
        label += f" Keep: {', '.join(ref['keep_elements'])}"
    return label


def main() -> int:
    if not FIXTURE.exists():
        print(f"FAIL: fixture missing {FIXTURE}", file=sys.stderr)
        return 1

    label = build_exact_background_label(FIXTURE)

    # 사전 조건 — fixture label 안에 'face framing' substring 이 실제로 있어
    # 회귀가 의미있는 케이스인지 검증
    if "face framing" not in label.lower():
        print(f"FAIL: fixture label 에 'face framing' 부재 — D2 회귀 패턴 아님:\n  {label}", file=sys.stderr)
        return 1

    res = resolve_ref_roles([(label, b"<bytes>")])

    if not any("BACKGROUND from a previous shot (SAME ROOM)" in r for r in res.ref_roles):
        print(f"FAIL: bg 분기 미매치 — ref_roles={res.ref_roles}", file=sys.stderr)
        return 1

    if any("character appearance reference" in i for i in res.ref_instructions):
        print(f"FAIL: character 분기 누설 — ref_instructions={res.ref_instructions}", file=sys.stderr)
        return 1

    print("OK: g4_6 label routing hotfix — D2 fixture (S1_Shot5 exact_background) verified")
    return 0


if __name__ == "__main__":
    sys.exit(main())
