"""
Basic health monitoring example.

This example demonstrates how to set up simple health monitoring
for a few web services with minimal configuration.
"""

import json
import time
from openHealth import HealthChecker


def create_basic_config():
    """Create a basic configuration file for demonstration."""
    config = {
        "services": [
            {
                "name": "Google Search",
                "url": "https://api.identity.codemate.ai",
                "health_endpoint": "/health",
                "interval": 60,
                "timeout": 10,
                "max_retries": 2,
                "expected_status_code": 200,
                "web_interface": {
                    "enabled": True
                },
                "slack_integration": {
                    "enabled": False,
                    "channel": "alerts",
                    "api_key": "your-slack-api-key",
                    "message_template": "Service {name} is down. Status: {status}"
                },
                "email_alert": {
                    "enabled": False,
                    "recipients": ["admin@example.com"],
                    "smtp_server": "smtp.gmail.com",
                    "smtp_port": 587,
                    "username": "monitor@example.com",
                    "app_password": "your-app-password"
                }
            },
            {
                "name": "HTTPBin Status",
                "url": "https://analytics.v3.codemate.ai",
                "health_endpoint": "/health",
                "interval": 30,
                "timeout": 5,
                "max_retries": 3,
                "expected_status_code": 200,
                "web_interface": {
                    "enabled": True
                },
                "slack_integration": {
                    "enabled": False,
                    "channel": "alerts",
                    "api_key": "your-slack-api-key",
                    "message_template": "Service {name} is down. Status: {status}"
                },
                "email_alert": {
                    "enabled": False,
                    "recipients": ["admin@example.com"],
                    "smtp_server": "smtp.gmail.com",
                    "smtp_port": 587,
                    "username": "monitor@example.com",
                    "app_password": "your-app-password"
                }
            }
        ]
    }
    
    with open("basic_config.json", "w") as f:
        json.dump(config, f, indent=2)
    
    print("Created basic_config.json")
    return "basic_config.json"


def main():
    """Demonstrate basic monitoring usage."""
    print("=== Basic Health Monitoring Example ===\n")
    
    # Create configuration
    config_file = create_basic_config()
    
    # Create custom callback to show results
    def status_callback(result):
        status_icon = "✅" if result.is_healthy() else "⚠️" if result.status == 'unhealthy' else "🚨"
        print(f"{status_icon} {result.service_name}: {result.status} ({result.response_time * 1000:.1f}ms)")
    
    # Initialize health checker
    print("Initializing health checker...")
    checker = HealthChecker(
        config_path=config_file,
        log_level="INFO"
    )
    
    # Add status callback
    checker.add_status_callback(status_callback)
    
    try:
        # Perform initial check
        print("\nPerforming initial health checks...")
        results = checker.check_all_services()
        
        print(f"\nChecked {len(results)} services:")
        for name, result in results.items():
            print(f"  • {name}: {result.status}")
        
        # Start continuous monitoring
        print("\nStarting continuous monitoring (Press Ctrl+C to stop)...")
        print("Web dashboard will be available at: http://localhost:8080")
        
        checker.start()
        
        # Keep running for demonstration
        try:
            while True:
                time.sleep(10)
                
                # Show periodic summary
                status = checker.get_status()
                healthy = sum(1 for s in status.values() if s['status'] == 'healthy')
                total = len(status)
                print(f"\n📊 Status Summary: {healthy}/{total} services healthy")
                
        except KeyboardInterrupt:
            print("\nReceived interrupt signal...")
    
    finally:
        # Clean up
        print("Stopping health checker...")
        checker.stop()
        print("Health checker stopped.")


if __name__ == "__main__":
    main()