"""Live OpenAI integration tests — skipped when OPENAI_API_KEY is absent."""

from __future__ import annotations

import os

import pytest
from django.conf import settings

from apps.repository.documents import services
from apps.repository.documents.models import Document

pytestmark = pytest.mark.skipif(
    not os.environ.get("OPENAI_API_KEY") and not getattr(settings, "OPENAI_API_KEY", ""),
    reason="OPENAI_API_KEY not set — skipping live LangChain tests.",
)


@pytest.mark.django_db
def test_live_summarise_returns_non_stub_text(submitter_user, public_collection, sample_pdf):
    from apps.repository.analytics.ai_insights import summarise_document

    doc = services.ingest_document(
        file=sample_pdf,
        title="Climate adaptation in smallholder maize systems",
        collection=public_collection,
        document_type=Document.DocumentType.THESIS,
        abstract="",
        submitted_by=submitter_user,
        actor=submitter_user,
    )
    # Give the chain real text to summarise.
    Document.objects.filter(pk=doc.pk).update(
        extracted_text=(
            "Smallholder farmers in the East African highlands face increasing "
            "climate variability. This thesis examines adaptation strategies "
            "including drought-tolerant seed varieties, agroforestry integration, "
            "water harvesting, and cooperative insurance schemes. Field data from "
            "three watersheds in Uganda and Kenya collected between 2019 and 2024 "
            "is analysed using mixed-methods. Findings show that combined "
            "interventions deliver 28% higher yield stability than single measures."
        )
    )
    insight = summarise_document(doc.pk)
    assert insight is not None
    assert insight.model_used != "stub"
    assert len(insight.payload["summary"]) > 60


@pytest.mark.django_db
def test_live_classify_picks_valid_slug(submitter_user, public_collection, sample_pdf):
    from apps.repository.analytics.ai_insights import classify_document

    doc = services.ingest_document(
        file=sample_pdf,
        title="Policy brief: drought-tolerant seed certification harmonisation",
        collection=public_collection,
        document_type=Document.DocumentType.POLICY_BRIEF,
        abstract="Recommendations for harmonising seed certification across member states.",
        submitted_by=submitter_user,
        actor=submitter_user,
    )
    insight = classify_document(doc.pk)
    assert insight is not None
    assert insight.model_used != "stub"
    assert insight.payload["suggested_collection_slug"]
    assert len(insight.payload["keywords"]) >= 3
