"""AI Summary API tests"""

import pytest


@pytest.mark.asyncio
async def test_ai_generate_no_key(client, auth_headers):
    """POST /api/v1/ai/generate/{pmid} — 404 if not seeded, 503 if seeded but no API key"""
    r = await client.post("/api/v1/ai/generate/39000101", headers=auth_headers)
    assert r.status_code in (200, 404, 503)  # 404 if pmid not seeded in test db


@pytest.mark.asyncio
async def test_ai_generate_unauthorized(client):
    """POST without auth should be rejected"""
    r = await client.post("/api/v1/ai/generate/39000101")
    # CSRF blocks unauthenticated requests with 403; either way not 200
    assert r.status_code in (401, 403, 404)


@pytest.mark.asyncio
async def test_ai_preview_seeded(client, db, auth_headers):
    """GET /api/v1/ai/preview/{pmid} — 200 with cached AI summary"""
    from app.models.literature import GlobalLiterature

    pmid = 39000999
    lit = GlobalLiterature(
        pmid=pmid,
        title="Test Article for AI Summary Preview",
        abstract="Test abstract for preview.",
        mesh_headings=[{"ai_summary": "Test AI summary text"}],
    )
    db.add(lit)
    await db.commit()

    r = await client.get(f"/api/v1/ai/preview/{pmid}", headers=auth_headers)
    assert r.status_code == 200
    data = r.json()
    assert "summaries" in data
    assert "Test AI summary text" in data["summaries"]


@pytest.mark.asyncio
async def test_ai_preview_unauthorized(client):
    """GET /api/v1/ai/preview/{pmid} without auth should be rejected"""
    r = await client.get("/api/v1/ai/preview/39000998")
    assert r.status_code in (401, 403, 404)


@pytest.mark.asyncio
async def test_ai_batch_generate(client, auth_headers):
    """POST /api/v1/ai/batch-generate — 200 with generated/total fields"""
    r = await client.post("/api/v1/ai/batch-generate", headers=auth_headers)
    assert r.status_code == 200
    data = r.json()
    assert "generated" in data
    assert "total" in data

    # Test with optional limit parameter
    r2 = await client.post("/api/v1/ai/batch-generate?limit=5", headers=auth_headers)
    assert r2.status_code == 200
    data2 = r2.json()
    assert "generated" in data2
    assert "total" in data2
