"""Acceptance test: Phase 1 RAG query with real Qwen LLM.

Prerequisites:
- ChromaDB running (local or docker)
- .env configured with valid LLM_BASE_URL and LLM_API_KEY
- Test documents ingested via /api/v1/ingest
"""
import os
import tempfile
import pytest
from fastapi.testclient import TestClient


@pytest.fixture
def client():
    """Create test client with real dependencies."""
    from app.main import app
    return TestClient(app)


@pytest.fixture
def ingested_document(client):
    """Create and ingest a test document for querying."""
    with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
        f.write("Python is a high-level programming language.\n")
        f.write("It was created by Guido van Rossum and first released in 1991.\n")
        f.write("Python emphasizes code readability with its use of significant indentation.\n")
        f.write("It supports multiple programming paradigms including structured and object-oriented.\n")
        path = f.name

    try:
        with open(path, 'rb') as f:
            response = client.post(
                "/api/v1/ingest",
                files={"file": ("python_info.txt", f, "text/plain")},
            )
        assert response.status_code == 200
        yield response.json()["document_id"]
    finally:
        os.unlink(path)


@pytest.mark.acceptance
@pytest.mark.slow
def test_query_with_real_llm(client, ingested_document):
    """Query should return bullet-point answer from actual LLM."""
    response = client.post(
        "/api/v1/query",
        json={"question": "Who created Python and when was it released?"},
    )

    assert response.status_code == 200
    data = response.json()

    assert "keywords" in data
    assert len(data["keywords"]) > 0

    assert "answer" in data
    assert len(data["answer"]) > 0

    assert "sources" in data
    assert len(data["sources"]) > 0

    source = data["sources"][0]
    assert "filename" in source
    assert "upload_date" in source
    assert "content_summary" in source

    print(f"Keywords: {data['keywords']}")
    print(f"Answer: {data['answer']}")
    print(f"Sources: {data['sources']}")


@pytest.mark.acceptance
@pytest.mark.slow
def test_query_keywords_displayed(client, ingested_document):
    """Verify response includes extracted keywords from question."""
    response = client.post(
        "/api/v1/query",
        json={"question": "What programming paradigms does Python support?"},
    )

    assert response.status_code == 200
    data = response.json()

    assert "keywords" in data
    keywords = data["keywords"]
    assert len(keywords) > 0

    assert "answer" in data
    answer = data["answer"]
    assert len(answer) > 0

    print(f"Extracted keywords: {keywords}")
    print(f"LLM Answer:\n{answer}")

    assert len(keywords) > 0
    assert any(
        kw.lower() in ("python", "programming", "paradigms", "support")
        for kw in keywords
    ), f"Expected relevant keywords but got: {keywords}"
