#!/usr/bin/env python3
"""
Test SDK with mock server to verify user experience
"""
import asyncio
import sys
import os
from aiohttp import web
import threading
import time

# Add the SDK to path for testing
sys.path.insert(0, r'C:\Sector 8\sector8-sdk\src')

from sector8 import setup

async def handle_telemetry(request):
    """Mock telemetry endpoint"""
    data = await request.json()
    return web.json_response({
        'status': 'success',
        'telemetry_id': 'telem_12345',
        'message': 'Telemetry data received',
        'received_data': {
            'provider': data.get('provider'),
            'model': data.get('model'),
            'tokens': data.get('tokens_used'),
            'cost': data.get('cost')
        }
    })

async def handle_threat_alert(request):
    """Mock threat alert endpoint"""
    data = await request.json()
    return web.json_response({
        'status': 'success',
        'alert_id': 'alert_67890',
        'message': 'Threat alert processed',
        'severity': data.get('severity')
    })

async def handle_incident_log(request):
    """Mock incident log endpoint"""
    data = await request.json()
    return web.json_response({
        'status': 'success',
        'incident_id': 'incident_11111',
        'message': 'Incident log processed',
        'severity': data.get('severity')
    })

async def handle_health(request):
    """Health check endpoint"""
    return web.json_response({'status': 'healthy', 'service': 'sector8-mock'})

def create_mock_server():
    """Create mock API server"""
    app = web.Application()
    app.router.add_post('/api/v1/telemetry', handle_telemetry)
    app.router.add_post('/api/v1/threat-alerts', handle_threat_alert)
    app.router.add_post('/api/v1/incident-logs', handle_incident_log)
    app.router.add_get('/health', handle_health)
    return app

async def run_mock_server():
    """Run the mock server"""
    app = create_mock_server()
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, 'localhost', 9876)
    await site.start()
    print("Mock API server started on http://localhost:9876")
    return runner

async def test_sdk_with_mock():
    """Test SDK against mock server"""
    print("=== Testing Sector8 SDK from User Perspective ===\n")
    
    # Start mock server
    mock_runner = await run_mock_server()
    await asyncio.sleep(1)  # Give server time to start
    
    try:
        # Test SDK initialization
        print("1. Testing SDK initialization...")
        client = setup(
            api_key="sk-test-key-for-demo-purposes-12345",
            base_url="http://localhost:9876",
            allow_unsafe_base_url=True,
        )
        print("   SUCCESS: SDK initialized successfully\n")
        
        # Test telemetry tracking
        print("2. Testing telemetry tracking...")
        telemetry_result = await client.save_telemetry(
            provider="openai",
            model="gpt-4",
            prompt="What is the weather today?",
            completion="I don't have access to real-time weather data.",
            tokens_used=42,
            latency_ms=850,
            cost=0.002
        )
        print("   SUCCESS: Telemetry data sent")
        print(f"   Response: {telemetry_result}\n")
        
        # Test threat alert
        print("3. Testing threat alert...")
        alert_result = await client.save_threat_alert(
            threat_type="prompt_injection",
            severity="High",
            status="detected",
            description="Suspicious prompt detected in user input"
        )
        print("   SUCCESS: Threat alert sent")
        print(f"   Response: {alert_result}\n")
        
        # Test incident log
        print("4. Testing incident log...")
        incident_result = await client.save_incident_log(
            severity="Critical",
            tool="openai",
            classification="data_breach", 
            details="Potential PII exposure detected",
            issue="unauthorized_data_access",
            tokens=15
        )
        print("   SUCCESS: Incident log sent")
        print(f"   Response: {incident_result}\n")
        
        # Cleanup
        await client.close()
        print("5. Client cleanup completed\n")
        
        print("=== ALL TESTS PASSED ===")
        print("The SDK works correctly from a user perspective!")
        
    except Exception as e:
        print(f"ERROR: {type(e).__name__}: {e}")
    
    finally:
        # Stop mock server
        await mock_runner.cleanup()

if __name__ == "__main__":
    asyncio.run(test_sdk_with_mock())
