"""인물 리스팅만 — 변형 없이, 1회 호출. Gemini Pro + GPT."""

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

from app.modules.llm.llm_client import call_structured
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}"

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

from app.core.database import SessionLocal
from app.models.project import Episode
from sqlalchemy.orm import undefer
db = SessionLocal()
ep = db.query(Episode).options(undefer(Episode.fulltext)).filter(Episode.id == EID).first()
ft = ep.fulltext
db.close()

parts = []
for s in seg["data"]["segments"]:
    text = s.get("text") or ft[s["start_char"]:s["end_char"]]
    parts.append(f"[씬 {s['scene_index']}]\n{text}")
scene_block = "\n\n".join(parts)

schema = {
    "type": "object",
    "properties": {
        "characters": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {"type": "string", "description": "인물 이름"},
                    "appearance_count": {"type": "integer", "description": "시각적 출현 횟수"}
                },
                "required": ["name", "appearance_count"],
                "additionalProperties": False
            }
        }
    },
    "required": ["characters"],
    "additionalProperties": False
}

system = """시나리오에서 등장하는 인물을 모두 나열하세요.

## 인물의 정의
- 시각적으로 카메라에 찍히며, 머리와 몸이 구분되는 모든 존재 (인간, 요괴, 동물, 로봇, 외계인 등)
- 단, 서사가 있어야 함 (행동이나 대사가 있는 존재만)
- 이미지 일관성을 위함이기 때문에 여러번 출현하는 경우만 추출

## 통합 규칙
- 종족명/형태명과 개인명이 같은 인물이면 반드시 하나로 통합
- 동일 인물의 별칭, 호칭, 종족명은 분리하지 말 것

## 출력 규칙
- name: 인물의 이름
- appearance_count: 시각적으로 카메라에 찍히는 출현 횟수"""

print(f"입력: {len(seg['data']['segments'])}씬, {len(scene_block)}자")

for step, label in [("beat_extract", "Gemini Pro"), ("visual_world_rules", "GPT")]:
    print(f"\n=== {label} ===")
    try:
        result = call_structured(
            step=step,
            system_prompt=system,
            user_prompt=scene_block,
            response_schema=schema,
            schema_name=f"char_list_{step}",
        )
        chars = result["characters"]
        chars.sort(key=lambda c: -c["appearance_count"])
        print(f"인물: {len(chars)}명")
        for c in chars:
            print(f"  {c['name']:20s} [{c['appearance_count']:3d}회]")
    except Exception as e:
        print(f"  ERROR: {e}")
