"""The embed_repository_documents backfill command targets the right documents
and delegates to ai_insights.embed_document_chunks.

The actual chunk/embed internals (token splitter + pgvector) live in ai_insights
and need network + pgvector, so here we assert the command's *selection* logic
(published-only by default, --all includes drafts, --limit caps) with the
embedding call mocked.
"""

from __future__ import annotations

from unittest.mock import patch

import pytest
from django.core.management import call_command


def _make(collection, pid, status):
    from apps.repository.documents.models import Document

    return Document.objects.create(
        title=f"Doc {pid}", abstract="text", collection=collection,
        status=status, public_document_id=pid,
    )


@pytest.mark.django_db
def test_embed_command_targets_published_only(public_collection):
    from apps.repository.documents.models import Document

    pub = _make(public_collection, "REPO-EMB-PUB", Document.Status.PUBLISHED)
    draft = _make(public_collection, "REPO-EMB-DRAFT", Document.Status.DRAFT)

    with patch("apps.repository.analytics.ai_insights.embed_document_chunks", return_value=2) as m:
        call_command("embed_repository_documents")

    called = {c.args[0] for c in m.call_args_list}
    assert pub.pk in called
    assert draft.pk not in called


@pytest.mark.django_db
def test_embed_command_all_includes_drafts(public_collection):
    from apps.repository.documents.models import Document

    pub = _make(public_collection, "REPO-EMB-PUB2", Document.Status.PUBLISHED)
    draft = _make(public_collection, "REPO-EMB-DRAFT2", Document.Status.DRAFT)

    with patch("apps.repository.analytics.ai_insights.embed_document_chunks", return_value=1) as m:
        call_command("embed_repository_documents", "--all")

    called = {c.args[0] for c in m.call_args_list}
    assert {pub.pk, draft.pk}.issubset(called)


@pytest.mark.django_db
def test_embed_command_respects_limit(public_collection):
    from apps.repository.documents.models import Document

    for i in range(3):
        _make(public_collection, f"REPO-EMB-L{i}", Document.Status.PUBLISHED)

    with patch("apps.repository.analytics.ai_insights.embed_document_chunks", return_value=1) as m:
        call_command("embed_repository_documents", "--limit", "2")

    assert m.call_count == 2
