"""Acceptance test: Phase 1 document ingestion with real ChromaDB.

Prerequisites:
- ChromaDB running with persistent storage
- Test files available (we create temporary text files)
- backend/.env configured
"""
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 sample_text_file():
    """Create a temporary text file for ingestion testing."""
    with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
        f.write("This is a test document about artificial intelligence.\n")
        f.write("Machine learning is a subset of AI.\n")
        f.write("Deep learning uses neural networks.\n")
        f.write("Natural language processing enables machines to understand text.\n")
        f.write("Computer vision allows machines to interpret images.\n")
        path = f.name
    yield path
    os.unlink(path)


@pytest.mark.acceptance
@pytest.mark.slow
def test_ingest_text_with_real_chromadb(client, sample_text_file):
    """Should ingest text file and create entries in real ChromaDB."""
    with open(sample_text_file, 'rb') as f:
        response = client.post(
            "/api/v1/ingest",
            files={"file": ("test_doc.txt", f, "text/plain")},
        )

    assert response.status_code == 200
    data = response.json()
    assert "document_id" in data
    assert data["chunk_count"] > 0
    assert data["filename"] == "test_doc.txt"

    # Verify document was actually stored in ChromaDB
    from app.core.database import get_chroma_client, get_or_create_collection
    chroma_client = get_chroma_client()
    collection = get_or_create_collection(chroma_client, "documents")

    # Query with a relevant keyword to verify embedding worked
    results = collection.query(
        query_texts=["artificial intelligence"],
        n_results=5,
    )

    assert len(results["documents"][0]) > 0
    assert any("artificial intelligence" in doc.lower() for doc in results["documents"][0])


@pytest.mark.acceptance
@pytest.mark.slow
def test_ingest_metadata_in_chromadb(client, sample_text_file):
    """Should store metadata with real embedding pipeline."""
    with open(sample_text_file, 'rb') as f:
        response = client.post(
            "/api/v1/ingest",
            files={"file": ("test_doc.txt", f, "text/plain")},
        )

    assert response.status_code == 200

    # Verify metadata was stored
    from app.core.database import get_chroma_client, get_or_create_collection
    chroma_client = get_chroma_client()
    collection = get_or_create_collection(chroma_client, "documents")

    results = collection.query(
        query_texts=["machine learning"],
        n_results=5,
        include=["metadatas"],
    )

    assert len(results["metadatas"][0]) > 0
    metadata = results["metadatas"][0][0]
    assert "filename" in metadata
    assert "upload_date" in metadata
    assert "content_summary" in metadata
