"""#6 검증 (커밋 금지) — resolved_entities 캐릭터/썸네일 커버리지 BEFORE(구코드
uvicorn HTTP) vs AFTER(신코드 직접 호출)."""
import sys
from collections import Counter
from pathlib import Path

import requests

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from app.core.database import SessionLocal  # noqa: E402
from app.api.v1.entities import list_stills  # noqa: E402

PROJECT_ID = "0e07d5e3-3fdd-4b9b-a54f-33aa59a5e204"
EPISODE_ID = "92910173-fd2c-46ad-9d60-2b02dead4c0c"
BASE = "http://localhost:8000/api/v1"


def summarize(rows, tag):
    c = Counter()
    for r in rows:
        res = r.get("resolved_entities") or []
        if not r.get("visible_entities_json") or r["visible_entities_json"] in ("[]", ""):
            continue
        c["stills_with_ve"] += 1
        types = {e["entity_type"] for e in res}
        if any(t in ("character", "composite") for t in types):
            c["with_char_entry"] += 1
        if any(e["entity_type"] in ("character", "composite") and e.get("reference_image_id") for e in res):
            c["with_char_thumb"] += 1
        if any(e["entity_type"] in ("prop", "location") and e.get("reference_image_id") for e in res):
            c["with_proploc_thumb"] += 1
        c["total_entries"] += len(res)
        c["entries_with_thumb"] += sum(1 for e in res if e.get("reference_image_id"))
    print(f"[{tag}] {dict(c)}")


def main():
    s = requests.Session()
    login = s.post(f"{BASE}/auth/login", json={"username": "admin", "password": "admin123"})
    print("login:", login.status_code)
    r = s.get(f"{BASE}/projects/{PROJECT_ID}/episodes/{EPISODE_ID}/stills")
    print("HTTP:", r.status_code)
    if r.status_code == 200:
        summarize(r.json()["stills"], "BEFORE(uvicorn old)")

    db = SessionLocal()
    try:
        rows = list_stills(EPISODE_ID, PROJECT_ID, db, None)["stills"]
        summarize(rows, "AFTER(new direct)")
        # S12 샘플 상세
        for row in rows:
            if row.get("scene_index") == 12 and row.get("shot_index") in (10, 16):
                ents = [
                    (e["entity_type"], e["display_name"], bool(e.get("reference_image_id")))
                    for e in (row.get("resolved_entities") or [])
                ]
                print(f"S12 sh{row['shot_index']}: {ents}")
    finally:
        db.close()


if __name__ == "__main__":
    main()
