"""백련의 씬별 복장 변화 추적 — gemini flash lite로 확인."""

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_texts = []
for s in segments:
    text = s.get("text", "")
    if "백련" in text:
        scene_texts.append(f"[씬 {s['scene_index']}]\n{text}")

scene_block = "\n\n".join(scene_texts)
print(f"백련 등장 씬: {len(scene_texts)}개, 총 {len(scene_block)}자")

schema = {
    "type": "object",
    "properties": {
        "scenes": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "scene_index": {"type": "integer"},
                    "costume": {"type": "string", "description": "이 씬에서 백련의 복장. 원문에 명시되지 않으면 '언급 없음'"},
                    "evidence": {"type": "string", "description": "복장 판단 근거 (원문 인용 또는 추론)"}
                },
                "required": ["scene_index", "costume", "evidence"],
                "additionalProperties": False
            }
        }
    },
    "required": ["scenes"],
    "additionalProperties": False
}

result = call_structured(
    step="text_cleanup",  # gemini-lite
    system_prompt="시나리오 원문을 읽고, 백련이라는 캐릭터의 씬별 복장/외형 변화를 추적하세요. 원문에 명시적으로 복장이 언급된 경우만 기록하고, 언급이 없으면 '언급 없음'으로 표시하세요.",
    user_prompt=f"아래 씬들에서 '백련'의 복장/외형이 어떻게 묘사되는지 씬별로 정리하세요.\n\n{scene_block}",
    response_schema=schema,
    schema_name="costume_trace",
)

print("\n=== 백련 씬별 복장 ===")
for s in result["scenes"]:
    marker = "✓" if s["costume"] != "언급 없음" else "·"
    print(f"  {marker} 씬{s['scene_index']:2d}: {s['costume']:30s}  ({s['evidence'][:60]})")
