#!/usr/bin/env python3
"""
Test script for the email notification system.
This script demonstrates how to test the email notification functionality.
"""

import os
import sys
import logging
from datetime import datetime

# Add the project root to the Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def test_email_configuration():
    """Test basic email configuration"""
    try:
        from utils.email_notifier import test_email_configuration
        
        logger.info("Testing email configuration...")
        success = test_email_configuration()
        
        if success:
            logger.info("✅ Email configuration test PASSED")
            return True
        else:
            logger.error("❌ Email configuration test FAILED")
            return False
            
    except Exception as e:
        logger.error(f"❌ Error testing email configuration: {str(e)}")
        return False

def test_critical_error_notification():
    """Test critical error notification"""
    try:
        from utils.email_notifier import send_critical_error_notification
        
        logger.info("Testing critical error notification...")
        
        # Simulate a critical error
        test_error = Exception("Test critical error for email notification system")
        
        success = send_critical_error_notification(
            error_type="TEST_ERROR",
            error_message="Test critical error notification from test script",
            context={
                "test": True,
                "script": "test_email_system.py",
                "timestamp": datetime.now().isoformat(),
                "environment": "test"
            },
            exception=test_error
        )
        
        if success:
            logger.info("✅ Critical error notification test PASSED")
            return True
        else:
            logger.error("❌ Critical error notification test FAILED")
            return False
            
    except Exception as e:
        logger.error(f"❌ Error testing critical error notification: {str(e)}")
        return False

def test_api_failure_notification():
    """Test API failure notification"""
    try:
        from utils.email_notifier import send_api_failure_notification
        
        logger.info("Testing API failure notification...")
        
        success = send_api_failure_notification(
            api_name="Test API",
            endpoint="/test/endpoint",
            error_message="Test API failure for email notification system",
            status_code=500,
            response_data={"error": "Internal Server Error", "code": "TEST_ERROR"},
            request_data={"method": "GET", "url": "/test/endpoint", "headers": {"Content-Type": "application/json"}}
        )
        
        if success:
            logger.info("✅ API failure notification test PASSED")
            return True
        else:
            logger.error("❌ API failure notification test FAILED")
            return False
            
    except Exception as e:
        logger.error(f"❌ Error testing API failure notification: {str(e)}")
        return False

def test_system_alert():
    """Test system alert notification"""
    try:
        from utils.email_notifier import send_system_alert
        
        logger.info("Testing system alert notification...")
        
        success = send_system_alert(
            alert_type="PERFORMANCE_WARNING",
            message="Test system alert for email notification system",
            severity="WARNING",
            context={
                "test": True,
                "script": "test_email_system.py",
                "timestamp": datetime.now().isoformat(),
                "performance_metric": "response_time",
                "value": "5.2s",
                "threshold": "3.0s"
            }
        )
        
        if success:
            logger.info("✅ System alert notification test PASSED")
            return True
        else:
            logger.error("❌ System alert notification test FAILED")
            return False
            
    except Exception as e:
        logger.error(f"❌ Error testing system alert notification: {str(e)}")
        return False

def test_error_monitoring():
    """Test error monitoring decorators"""
    try:
        from utils.error_monitor import monitor_critical_system, monitor_openai_api
        
        logger.info("Testing error monitoring decorators...")
        
        @monitor_critical_system("test_function")
        def test_function():
            raise Exception("Test exception for monitoring system")
        
        try:
            test_function()
        except Exception:
            # Expected to raise exception
            pass
        
        logger.info("✅ Error monitoring decorator test PASSED")
        return True
        
    except Exception as e:
        logger.error(f"❌ Error testing error monitoring: {str(e)}")
        return False

def main():
    """Run all tests"""
    logger.info("🚀 Starting Email Notification System Tests")
    logger.info("=" * 50)
    
    tests = [
        ("Email Configuration", test_email_configuration),
        ("Critical Error Notification", test_critical_error_notification),
        ("API Failure Notification", test_api_failure_notification),
        ("System Alert Notification", test_system_alert),
        ("Error Monitoring", test_error_monitoring)
    ]
    
    results = []
    
    for test_name, test_func in tests:
        logger.info(f"\n📋 Running test: {test_name}")
        try:
            result = test_func()
            results.append((test_name, result))
        except Exception as e:
            logger.error(f"❌ Test '{test_name}' failed with exception: {str(e)}")
            results.append((test_name, False))
    
    # Summary
    logger.info("\n" + "=" * 50)
    logger.info("📊 TEST SUMMARY")
    logger.info("=" * 50)
    
    passed = 0
    total = len(results)
    
    for test_name, result in results:
        status = "✅ PASSED" if result else "❌ FAILED"
        logger.info(f"{test_name}: {status}")
        if result:
            passed += 1
    
    logger.info(f"\nResults: {passed}/{total} tests passed")
    
    if passed == total:
        logger.info("🎉 All tests passed! Email notification system is working correctly.")
        return 0
    else:
        logger.error(f"⚠️ {total - passed} tests failed. Please check your email configuration.")
        return 1

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)
