"""
Test Task 2.1: Async Analytics Writing

This test verifies that analytics writes happen asynchronously and don't block the response.
"""

import asyncio
import time
from unittest.mock import MagicMock, patch
import pytest


@pytest.mark.asyncio
async def test_async_analytics_improves_response_time():
    """
    Verify that async analytics writing improves response time.
    
    The response should return immediately without waiting for DB writes.
    """
    # Mock the analytics write to take 100ms (simulating slow DB write)
    async def slow_analytics_write(*args, **kwargs):
        await asyncio.sleep(0.1)  # 100ms delay
        return 123  # mock analytics_id
    
    with patch('backend.api.routes.complete._write_analytics_async', side_effect=slow_analytics_write):
        # The response should return almost immediately
        # If it was synchronous, it would take 100ms+
        start_time = time.time()
        
        # Simulate creating the async task (what the actual code does)
        task = asyncio.create_task(slow_analytics_write())
        
        # Response returns immediately (don't await the task)
        elapsed = time.time() - start_time
        
        # Response should return in <10ms (not waiting for 100ms DB write)
        assert elapsed < 0.01, f"Response took {elapsed*1000:.1f}ms, should be <10ms"
        
        # Task completes eventually in background
        await task
        total_elapsed = time.time() - start_time
        assert total_elapsed >= 0.1, f"Task should take ~100ms, took {total_elapsed*1000:.1f}ms"


@pytest.mark.asyncio
async def test_analytics_write_is_non_blocking():
    """
    Verify that analytics write failures don't affect the response.
    """
    # Mock the analytics write to fail
    async def failing_analytics_write(*args, **kwargs):
        raise Exception("Database connection failed")
    
    with patch('backend.api.routes.complete._write_analytics_async', side_effect=failing_analytics_write):
        # Create task that will fail in background
        task = asyncio.create_task(failing_analytics_write())
        
        # Response should still succeed (not awaiting the task)
        # In real code, the response is returned before the task completes
        
        # Verify task fails as expected
        with pytest.raises(Exception, match="Database connection failed"):
            await task


def test_analytics_write_eventually_consistent():
    """
    Manual test instructions:
    
    1. Send a request via the API:
       curl -X POST http://localhost:8000/api/complete \\
         -H "Authorization: Bearer YOUR_API_KEY" \\
         -H "Content-Type: application/json" \\
         -d '{"messages": [{"role": "user", "content": "Hello"}], "model": "gpt-3.5-turbo"}'
    
    2. Verify response returns quickly (measure response time)
    
    3. Wait 1-2 seconds
    
    4. Query analytics table to verify the record was written:
       SELECT * FROM analytics WHERE subscription_id = YOUR_SUBSCRIPTION_ID 
       ORDER BY created_at DESC LIMIT 1;
    
    5. Verify the analytics record exists with correct data
    
    Expected Results:
    - Response time: 50-150ms faster than before Task 2.1
    - Analytics record appears in DB within 1-2 seconds
    - No errors in logs from async write task
    """
    pass


if __name__ == "__main__":
    print("Task 2.1 Test Suite: Async Analytics Writing")
    print("=" * 60)
    print()
    print("Automated tests:")
    pytest.main([__file__, "-v"])
    print()
    print("Manual test instructions:")
    print(test_analytics_write_eventually_consistent.__doc__)
