"""Phase 2.3 — controlled-vocabulary tag autocomplete (FRREP-MCL007).

Approved keywords surface for autocomplete and attach immediately; a brand-new
tag is accepted, queued PENDING for moderation, and does not attach to the
document (so it can't appear in browse facets) until a curator approves it.
"""
from __future__ import annotations

import pytest
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client
from django.urls import reverse

from apps.repository.documents.models import Document, Keyword

PDF_BYTES = (
    b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n1 0 obj<</Type/Catalog>>endobj\ntrailer<<>>\n%%EOF\n"
)


def _base_data(collection_pk):
    return {
        "title": "Soil carbon study",
        "abstract": "Carbon sequestration in agroforestry systems.",
        "document_type": Document.DocumentType.THESIS,
        "license_type": Document.License.CC_BY,
        "language": "en",
        "year": 2026,
        "collection": collection_pk,
        "authors_text": "Kato, Amina",
    }


# ── Keyword search endpoint ────────────────────────────────────────────────


@pytest.mark.django_db
def test_keyword_search_requires_login(client):
    resp = client.get(reverse("repo_documents:keyword_search"), {"q": "agro"})
    assert resp.status_code in (302, 403)


@pytest.mark.django_db
def test_keyword_search_returns_only_approved(submitter_user):
    Keyword.objects.create(label="Agroforestry", slug="agroforestry", status=Keyword.Status.APPROVED)
    Keyword.objects.create(label="Agrarian", slug="agrarian", status=Keyword.Status.PENDING)

    client = Client()
    client.force_login(submitter_user)
    resp = client.get(reverse("repo_documents:keyword_search"), {"q": "agr"})
    assert resp.status_code == 200
    labels = [r["label"] for r in resp.json()["results"]]
    assert "Agroforestry" in labels
    assert "Agrarian" not in labels  # pending is hidden from autocomplete


# ── Submission paths ───────────────────────────────────────────────────────


@pytest.mark.django_db
def test_submit_approved_tag_attaches_immediately(public_collection, submitter_user):
    Keyword.objects.create(label="Agroforestry", slug="agroforestry", status=Keyword.Status.APPROVED)
    client = Client()
    client.force_login(submitter_user)
    data = _base_data(public_collection.pk)
    data["keywords_text"] = "Agroforestry"
    data["file"] = SimpleUploadedFile("t.pdf", PDF_BYTES, content_type="application/pdf")

    resp = client.post(reverse("repo_documents:submit"), data=data)
    assert resp.status_code == 302
    doc = Document.objects.get()
    assert doc.keywords.filter(slug="agroforestry").exists()


@pytest.mark.django_db
def test_submit_new_tag_is_queued_pending_and_not_attached(
    public_collection, submitter_user
):
    client = Client()
    client.force_login(submitter_user)
    data = _base_data(public_collection.pk)
    data["keywords_text"] = "novel-soil-method"
    data["file"] = SimpleUploadedFile("t.pdf", PDF_BYTES, content_type="application/pdf")

    resp = client.post(reverse("repo_documents:submit"), data=data)
    assert resp.status_code == 302
    kw = Keyword.objects.get(slug="novel-soil-method")
    assert kw.status == Keyword.Status.PENDING
    doc = Document.objects.get()
    # Pending tags must not attach (so they can't show in browse facets yet).
    assert not doc.keywords.filter(slug="novel-soil-method").exists()
