"""Baseline ref-count snapshot — current ImageAsset reference state per entity.

PID/EID 의 ImageAsset (asset_type='reference') 를 entity short_id + type 별로
집계해 stdout 에 출력. fix 전 baseline 으로 기록 (uncommitted /tmp 권장).

스크립트 본문에 시나리오 의존 0건 — PID/EID 만 CLI 입력.

사용:

    backend/.venv/bin/python scripts/g4_6_baseline_refs.py \
      --pid <project_id> --eid <episode_id> > /tmp/g4_6_baseline_refs.txt
"""
from __future__ import annotations

import argparse
import sys
from collections import defaultdict
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
BACKEND = REPO_ROOT / "backend"
sys.path.insert(0, str(BACKEND))

from sqlalchemy import func  # noqa: E402

from app.core.database import SessionLocal  # noqa: E402
from app.models.project import EntityCanon, ImageAsset  # noqa: E402


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--pid", required=True)
    parser.add_argument("--eid", required=True)
    args = parser.parse_args()

    db = SessionLocal()
    try:
        rows = (
            db.query(
                EntityCanon.short_id,
                EntityCanon.entity_type,
                EntityCanon.name,
                func.count(ImageAsset.id).label("ref_count"),
                func.sum(ImageAsset.is_primary).label("primary_count"),
            )
            .outerjoin(
                ImageAsset,
                (ImageAsset.entity_id == EntityCanon.id)
                & (ImageAsset.asset_type == "reference")
                & (ImageAsset.episode_id == args.eid),
            )
            .filter(EntityCanon.project_id == args.pid)
            .group_by(EntityCanon.short_id, EntityCanon.entity_type, EntityCanon.name)
            .order_by(EntityCanon.entity_type, EntityCanon.short_id)
            .all()
        )

        per_type: dict[str, list[tuple]] = defaultdict(list)
        for r in rows:
            per_type[r.entity_type or "unknown"].append(r)

        print(f"# baseline ref snapshot — pid={args.pid} eid={args.eid}")
        print(f"# total entities: {len(rows)}")
        print()
        for etype in sorted(per_type.keys()):
            entries = per_type[etype]
            with_ref = sum(1 for r in entries if (r.ref_count or 0) > 0)
            with_primary = sum(1 for r in entries if (r.primary_count or 0) > 0)
            print(f"## {etype} — {len(entries)} entities, {with_ref} with ref, {with_primary} with primary")
            print(f"{'short_id':<10} {'name':<30} {'ref':>5} {'primary':>8}")
            for r in entries:
                short = r.short_id or "(null)"
                name = (r.name or "")[:30]
                ref = r.ref_count or 0
                primary = int(r.primary_count or 0)
                print(f"{short:<10} {name:<30} {ref:>5} {primary:>8}")
            print()
    finally:
        db.close()


if __name__ == "__main__":
    main()
