"""Backfill pgvector embeddings for the assistant's semantic Repository search.

The legacy migration created Documents directly (status set at create, no
`publish()` transition, no Celery worker), so the per-publish embedding signal
never fired and the corpus is unindexed. Run this once after a migration (and
any time you want to rebuild) so ``search_repository_documents`` does real RAG
instead of falling back to a title-only match.

    manage.py embed_repository_documents            # all published docs
    manage.py embed_repository_documents --limit 50 # smoke test
    manage.py embed_repository_documents --all      # include drafts too
"""

from __future__ import annotations

from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Embed Repository documents into pgvector for assistant semantic search."

    def add_arguments(self, parser):
        parser.add_argument("--limit", type=int, default=0, help="Embed at most N documents (0 = all).")
        parser.add_argument("--all", action="store_true", help="Include non-published documents.")

    def handle(self, *args, **opt):
        from apps.repository.analytics.ai_insights import embed_document_chunks
        from apps.repository.documents.models import Document

        qs = Document.objects.all() if opt["all"] else Document.objects.filter(
            status=Document.Status.PUBLISHED
        )
        ids = list(qs.order_by("id").values_list("id", flat=True))
        if opt["limit"]:
            ids = ids[: opt["limit"]]

        total = len(ids)
        self.stdout.write(f"Embedding {total} documents …")
        embedded = chunks = failed = 0
        for i, pk in enumerate(ids, 1):
            try:
                n = embed_document_chunks(pk)
                chunks += n
                embedded += 1 if n else 0
            except Exception as e:  # noqa: BLE001 — keep going on individual failures
                failed += 1
                self.stderr.write(f"  ! doc {pk}: {e}")
            if i % 100 == 0 or i == total:
                self.stdout.write(f"  …{i}/{total} ({embedded} embedded, {chunks} chunks, {failed} failed)")
                self.stdout.flush()

        self.stdout.write(self.style.SUCCESS(
            f"Done: {embedded}/{total} documents embedded · {chunks} chunks · {failed} failed"))
