"""
Integration tests for CPAP MCP Server.

These tests use mocked CPAP data to test the full workflow.
"""

import pytest
import base64
import json
from unittest.mock import Mock, patch
from datetime import datetime


# Mark as integration tests
pytestmark = pytest.mark.integration


@pytest.mark.asyncio
class TestFullWorkflow:
    """Test complete workflows from upload to analysis."""

    @patch('cpap_mcp.server.CPAPReader')
    async def test_complete_upload_and_query_workflow(self, mock_cpap_reader_class):
        """Test uploading files and querying data."""
        from cpap_mcp.server import (
            upload_file, get_devices, get_sessions, 
            get_session_details, clear_uploaded_files
        )
        
        # Setup mock reader
        mock_device = Mock()
        mock_device.model_dump.return_value = {
            "serial_number": "12345678",
            "model": "AirSense 10",
            "manufacturer": "ResMed"
        }
        
        mock_session = Mock()
        mock_session.session_id = "20240101_session1"
        mock_session.to_dict.return_value = {
            "session_id": "20240101_session1",
            "start_time": "2024-01-01T22:30:00",
            "duration_hours": 7.5
        }
        
        mock_reader = Mock()
        mock_reader.get_devices.return_value = [mock_device]
        mock_reader.get_sessions.return_value = [mock_session]
        mock_cpap_reader_class.return_value = mock_reader
        
        # Upload a file
        content = b"Test CPAP data file"
        content_b64 = base64.b64encode(content).decode('utf-8')
        result = await upload_file({
            "file_path": "DATALOG/20240101/test.edf",
            "content": content_b64
        })
        assert "Successfully uploaded" in result[0].text
        
        # Get devices
        result = await get_devices()
        data = json.loads(result[0].text)
        assert data["count"] == 1
        assert data["devices"][0]["serial_number"] == "12345678"
        
        # Get sessions
        result = await get_sessions({})
        data = json.loads(result[0].text)
        assert data["count"] == 1
        
        # Get session details
        result = await get_session_details({"session_id": "20240101_session1"})
        data = json.loads(result[0].text)
        assert data["session_id"] == "20240101_session1"
        
        # Clear files
        result = await clear_uploaded_files()
        assert "Successfully cleared" in result[0].text

    @patch('cpap_mcp.server.CPAPReader')
    async def test_therapy_analysis_workflow(self, mock_cpap_reader_class):
        """Test analyzing therapy effectiveness."""
        from cpap_mcp.server import upload_file, analyze_therapy_effectiveness
        
        # Setup mock reader with realistic data
        mock_reader = Mock()
        mock_reader.get_summary_statistics.return_value = {
            "sessions": [
                {"summary": {"duration_hours": 7.5, "ahi": 3.2, "leak_95th": 12}},
                {"summary": {"duration_hours": 6.8, "ahi": 4.1, "leak_95th": 15}},
                {"summary": {"duration_hours": 8.0, "ahi": 2.8, "leak_95th": 10}},
            ],
            "total_sessions": 3,
            "total_hours": 22.3,
            "average_hours_per_session": 7.43,
            "average_ahi": 3.37,
            "average_leak_95th": 12.33,
        }
        mock_cpap_reader_class.return_value = mock_reader
        
        # Upload file to initialize
        content_b64 = base64.b64encode(b"test").decode('utf-8')
        await upload_file({"file_path": "test.edf", "content": content_b64})
        
        # Analyze therapy
        result = await analyze_therapy_effectiveness({"days": 30})
        data = json.loads(result[0].text)
        
        assert "compliance" in data
        assert "therapy_effectiveness" in data
        assert "leak_performance" in data
        assert "recommendations" in data
        assert data["total_sessions"] == 3


@pytest.mark.asyncio 
class TestErrorHandling:
    """Test error handling in integration scenarios."""

    async def test_operations_without_uploaded_files(self):
        """Test that operations fail gracefully without data."""
        from cpap_mcp.server import get_devices, reset_reader
        import cpap_mcp.server as server_module
        
        # Reset state
        server_module.working_dir = None
        server_module.cpap_reader = None
        
        # get_devices returns default device even without uploaded files
        result = await get_devices()
        assert "devices" in result[0].text
        assert "UNKNOWN" in result[0].text

    @patch('cpap_mcp.server.CPAPReader')
    async def test_missing_session_handling(self, mock_cpap_reader_class):
        """Test handling of missing sessions."""
        from cpap_mcp.server import upload_file, get_session_details
        
        mock_reader = Mock()
        mock_reader.get_sessions.return_value = []
        mock_cpap_reader_class.return_value = mock_reader
        
        content_b64 = base64.b64encode(b"test").decode('utf-8')
        await upload_file({"file_path": "test.edf", "content": content_b64})
        
        # get_session_details raises ValueError for missing sessions
        with pytest.raises(ValueError, match="Session not found"):
            await get_session_details({"session_id": "nonexistent"})
