"""백련의 씬별 복장 변화 추적 — GPT 5.4로 추정 포함."""

import json
import sys
sys.path.insert(0, ".")

from app.modules.llm.llm_client import call_structured
from app.core.database import SessionLocal
from app.models.project import Episode
from sqlalchemy.orm import undefer
from app.core.config import settings

PID = "c0f47e88-b9f7-43a5-9e73-66b0f965b247"
EID = "d2d203b8-4865-40f0-b5a6-e5990fa3effd"
CP = f"{settings.projects_dir}/{PID}/checkpoints/episodes/{EID}"

db = SessionLocal()
ep = db.query(Episode).options(undefer(Episode.fulltext)).filter(Episode.id == EID).first()
ft = ep.fulltext
db.close()

seg = json.load(open(f"{CP}/scene_save/manifest.json"))
segments = seg["data"]["segments"]

# 백련 등장 씬 + 전후 컨텍스트를 위해 전체 전달
scene_block_parts = []
for s in segments:
    text = s.get("text", "")
    scene_block_parts.append(f"[씬 {s['scene_index']}]\n{text}")
scene_block = "\n\n".join(scene_block_parts)
print(f"전체 씬: {len(segments)}개, 총 {len(scene_block)}자")

schema = {
    "type": "object",
    "properties": {
        "scenes": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "scene_index": {"type": "integer"},
                    "costume": {"type": "string", "description": "이 씬에서 백련의 복장/외형. 원문에 명시되어 있으면 그대로, 없으면 문맥으로 추정"},
                    "source": {"type": "string", "enum": ["명시", "추정"], "description": "원문에 명시적으로 복장이 언급되었는지, 문맥으로 추정한 것인지"},
                    "reasoning": {"type": "string", "description": "판단 근거 (간단히)"}
                },
                "required": ["scene_index", "costume", "source", "reasoning"],
                "additionalProperties": False
            }
        }
    },
    "required": ["scenes"],
    "additionalProperties": False
}

result = call_structured(
    step="visual_world_rules",  # gpt 5.4
    system_prompt=(
        "시나리오 전문을 읽고, '백련'이라는 캐릭터가 등장하는 모든 씬에서의 복장/외형을 추적하세요.\n\n"
        "규칙:\n"
        "- 원문에 복장이 명시되면 source='명시'\n"
        "- 원문에 복장 언급이 없지만 전후 문맥으로 추정 가능하면 source='추정'으로 표시\n"
        "- 백련이 등장하지 않는 씬은 제외\n"
        "- 변신/변형(요기 해방, 혈안 등)도 외형 변화로 포함\n"
        "- 복장이 바뀌는 시점을 정확히 포착하세요"
    ),
    user_prompt=f"아래 시나리오 전문에서 '백련'의 씬별 복장/외형 변화를 추적하세요.\n\n{scene_block}",
    response_schema=schema,
    schema_name="costume_trace_gpt",
)

print("\n=== 백련 씬별 복장 (GPT 5.4) ===")
for s in result["scenes"]:
    marker = "✓" if s["source"] == "명시" else "?"
    print(f"  {marker} 씬{s['scene_index']:2d}: [{s['source']}] {s['costume']:35s}  {s['reasoning'][:70]}")
