import os
import httpx
import pytest

BASE_URL = os.getenv("SYNC_TEST_BASE_URL", "http://127.0.0.1:8002/api/v1")

@pytest.mark.skip(reason="Requires valid GEMINI_API_KEY")
def test_document_lifecycle():
    """
    Test creating, listing, and deleting a document.
    """
    doc_data = {
        "title": "Test Document Title",
        "text": "This is the content of the test document.",
        "source_url": "http://example.com",
        "author": "Test Author"
    }
    
    with httpx.Client(timeout=10.0) as client:
        # 1. Create Document
        r = client.post(f"{BASE_URL}/documents/", json=doc_data)
        assert r.status_code == 200, f"Expected 200 OK, got {r.status_code}: {r.text}"
        
        json_data = r.json()
        assert "message" in json_data
        assert "added successfully" in json_data["message"]
        
        # 2. List Documents
        r = client.get(f"{BASE_URL}/documents/")
        assert r.status_code == 200, f"Expected 200 OK, got {r.status_code}: {r.text}"
        
        docs = r.json().get("documents", [])
        assert len(docs) > 0, "No documents returned"
        
        # Find our document
        test_doc = None
        for doc in docs:
            if doc["title"] == doc_data["title"]:
                test_doc = doc
                break
                
        assert test_doc is not None, "Created document not found in list"
        doc_id = test_doc["id"]
        
        # 3. Delete Document
        r = client.delete(f"{BASE_URL}/documents/{doc_id}")
        assert r.status_code == 200, f"Expected 200 OK, got {r.status_code}: {r.text}"
        
        # 4. Verify Deletion
        r = client.get(f"{BASE_URL}/documents/")
        docs = r.json().get("documents", [])
        
        deleted_found = False
        for doc in docs:
            if doc["id"] == doc_id:
                deleted_found = True
                break
                
        assert not deleted_found, "Document was not deleted"
