"""#7 export SOT-first 검증 드라이버 (커밋 금지) — 실 generate_html_zip 실행 후
shot-refs 캡션 분포/샷별 참조 구성을 파싱해 '얼굴만 나옴' 해소를 실측."""
import re
import sys
import zipfile
from collections import Counter
from pathlib import Path

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

from app.core.database import SessionLocal  # noqa: E402
from app.services.export_service import ExportService  # noqa: E402

PROJECT_ID = "0e07d5e3-3fdd-4b9b-a54f-33aa59a5e204"
EPISODE_ID = "92910173-fd2c-46ad-9d60-2b02dead4c0c"
OUT = Path(__file__).resolve().parent / "export7_out"


def main():
    db = SessionLocal()
    try:
        svc = ExportService(db, PROJECT_ID, actor_id="claude-verify")
        zip_path = svc.generate_html_zip(EPISODE_ID)
        print("ZIP:", zip_path)
    finally:
        db.close()

    OUT.mkdir(exist_ok=True)
    with zipfile.ZipFile(zip_path) as zf:
        zf.extractall(OUT)
    htmls = sorted(OUT.rglob("*.html"))
    print("HTML files:", [h.name for h in htmls])
    label_counter: Counter = Counter()
    shots_with_refs = 0
    total_ref_items = 0
    for h in htmls:
        text = h.read_text(encoding="utf-8")
        for block in re.findall(r'<div class="shot-refs">.*?</div></div>', text, re.S):
            shots_with_refs += 1
            labels = re.findall(r'<div class="ref-label">([^<]*)</div>', block)
            total_ref_items += len(labels)
            label_counter.update(labels)
    print(f"shots_with_refs={shots_with_refs} total_ref_items={total_ref_items}")
    for lab, n in label_counter.most_common(30):
        print(f"  {n:3d}  {lab}")


if __name__ == "__main__":
    main()
