#!/usr/bin/env python3
"""
Simple test client to verify the CPAP MCP server is working.

This script creates a minimal test archive and sends it to the server.
"""

import asyncio
import base64
import zipfile
import io
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client


async def test_upload_archive():
    """Test uploading a CPAP data archive."""
    
    # Create a minimal test archive
    print("Creating test archive...")
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zipf:
        # Add some test files
        zipf.writestr('STR.edf', b'Test session summary data')
        zipf.writestr('DATALOG/20240101/20240101_220030_BRP.edf', b'Test BRP data')
        zipf.writestr('Identification.tgt', b'Test device ID')
    
    zip_content = zip_buffer.getvalue()
    content_b64 = base64.b64encode(zip_content).decode('utf-8')
    
    print(f"Archive size: {len(zip_content)} bytes")
    print(f"Base64 size: {len(content_b64)} bytes")
    
    # Connect to server
    print("\nConnecting to MCP server...")
    server_params = StdioServerParameters(
        command="python",
        args=["-m", "cpap_mcp.server"],
    )
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            
            # List available tools
            print("\nListing tools...")
            tools = await session.list_tools()
            print(f"Available tools: {len(tools.tools)}")
            for tool in tools.tools[:5]:
                print(f"  - {tool.name}")
            
            # Upload archive
            print("\nUploading archive...")
            result = await session.call_tool(
                "upload_archive",
                arguments={"content": content_b64}
            )
            
            print("\nServer response:")
            for item in result.content:
                if hasattr(item, 'text'):
                    print(item.text)
            
            # List uploaded files
            print("\nListing uploaded files...")
            result = await session.call_tool("list_uploaded_files", arguments={})
            
            print("\nServer response:")
            for item in result.content:
                if hasattr(item, 'text'):
                    print(item.text)
            
            print("\n✓ Test completed successfully!")


if __name__ == '__main__':
    asyncio.run(test_upload_archive())
