"""One-shot: dla istniejącego performera dorzuć TPDB external_ref po canonical UUID.

Użycie: python scripts/add_performer_tpdb_ref.py "<name>" <tpdb_uuid>
"""
import sys

from sqlalchemy import select

from app.db import session_scope
from app.models.performer import Performer, PerformerExternalRef
from app.models.source import Source, SourceKind


def main(name: str, tpdb_id: str) -> None:
    with session_scope() as session:
        perf = session.execute(
            select(Performer).where(Performer.canonical_name.ilike(name)).limit(1)
        ).scalar_one_or_none()
        if perf is None:
            print(f"performer not found: {name!r}")
            sys.exit(1)
        src = session.execute(
            select(Source).where(Source.kind == SourceKind.tpdb)
        ).scalar_one_or_none()
        if src is None:
            print("tpdb Source row missing")
            sys.exit(1)
        existing = session.execute(
            select(PerformerExternalRef).where(
                PerformerExternalRef.source_id == src.id,
                PerformerExternalRef.external_id == tpdb_id,
            )
        ).scalar_one_or_none()
        if existing:
            print(f"already exists: performer_id={existing.performer_id}")
            return
        session.add(
            PerformerExternalRef(
                source_id=src.id,
                external_id=tpdb_id,
                performer_id=perf.id,
                confidence=1.0,
            )
        )
        print(f"linked {perf.canonical_name} (id={perf.id}) ↔ tpdb:{tpdb_id}")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])
