#!/usr/bin/env python3
"""
Test Script für neue Features
- Streaming UI (SSE)
- Email Integration (IMAP/SMTP)
"""

import json
import sys

def test_imports():
    """Teste dass alle notwendigen Importe funktionieren"""
    print("✓ Testing Imports...")
    try:
        import imaplib
        import smtplib
        from email.mime.text import MIMEText
        from email.mime.multipart import MIMEMultipart
        from flask import Flask, Response
        print("  ✓ All imports successful")
        return True
    except ImportError as e:
        print(f"  ✗ Import Error: {e}")
        return False

def test_app_syntax():
    """Teste dass app.py syntaktisch korrekt ist"""
    print("\n✓ Testing app.py syntax...")
    try:
        import app
        print("  ✓ app.py loads successfully")
        
        # Check if new routes exist
        routes = [str(rule) for rule in app.app.url_map.iter_rules()]
        
        if '/api/agent-stream' in routes:
            print("  ✓ /api/agent-stream route exists")
        else:
            print("  ✗ /api/agent-stream route NOT found")
            
        if '/emails' in routes:
            print("  ✓ /emails route exists")
        else:
            print("  ✗ /emails route NOT found")
            
        return True
    except Exception as e:
        print(f"  ✗ Error: {e}")
        return False

def test_email_config():
    """Teste Email-Konfiguration"""
    print("\n✓ Testing Email Configuration...")
    import os
    
    config = {
        'IMAP_SERVER': os.getenv('IMAP_SERVER', 'imap.gmail.com'),
        'SMTP_SERVER': os.getenv('SMTP_SERVER', 'smtp.gmail.com'),
        'EMAIL_ADDRESS': os.getenv('EMAIL_ADDRESS', ''),
        'EMAIL_PASSWORD': os.getenv('EMAIL_PASSWORD', ''),
    }
    
    configured = bool(config['EMAIL_ADDRESS'] and config['EMAIL_PASSWORD'])
    status = "✓ Configured" if configured else "⚠ Not Configured"
    
    print(f"  {status}")
    print(f"    - IMAP: {config['IMAP_SERVER']}")
    print(f"    - SMTP: {config['SMTP_SERVER']}")
    print(f"    - Email: {config['EMAIL_ADDRESS'][:20] if config['EMAIL_ADDRESS'] else 'Not set'}...")
    
    if not configured:
        print("    Note: Set environment variables to enable email features")
    
    return True

def test_templates():
    """Teste dass neue Templates existieren"""
    print("\n✓ Testing Templates...")
    import os
    
    templates = {
        'emails.html': os.path.exists('templates/emails.html'),
        'orchestrator.html': os.path.exists('templates/orchestrator.html'),
    }
    
    for template, exists in templates.items():
        status = "✓" if exists else "✗"
        print(f"  {status} {template}")
    
    return all(templates.values())

def test_sse_response():
    """Teste SSE Response Header"""
    print("\n✓ Testing SSE Support...")
    try:
        from flask import Flask, Response
        
        app = Flask(__name__)
        
        @app.route('/test-sse')
        def test_sse():
            def generate():
                yield f"data: {json.dumps({'type': 'test'})}\n\n"
            return Response(generate(), mimetype='text/event-stream')
        
        print("  ✓ SSE Response configured")
        return True
    except Exception as e:
        print(f"  ✗ Error: {e}")
        return False

def main():
    print("=" * 60)
    print("🧪 Testing New Features")
    print("=" * 60)
    
    results = [
        ("Imports", test_imports()),
        ("App Syntax", test_app_syntax()),
        ("Email Config", test_email_config()),
        ("Templates", test_templates()),
        ("SSE Support", test_sse_response()),
    ]
    
    print("\n" + "=" * 60)
    print("📊 Test Summary")
    print("=" * 60)
    
    for name, result in results:
        status = "✓ PASS" if result else "✗ FAIL"
        print(f"{status}: {name}")
    
    passed = sum(1 for _, r in results if r)
    total = len(results)
    
    print(f"\nTotal: {passed}/{total} passed")
    
    if passed == total:
        print("\n✨ All tests passed!")
        return 0
    else:
        print("\n⚠️  Some tests failed")
        return 1

if __name__ == '__main__':
    sys.exit(main())
