"""
Minimal health checker demo script.
This script demonstrates the core health checking functionality.
"""

import json
import time
from openHealth import HealthChecker, load_config


def create_test_config():
    """Create a test configuration file with Slack notifications."""
    config = {
        "services": [
            {
                "name": "Base Model (bodh-x0) Test Service",
                "url": "http://34.31.180.53:2306",
                "health_endpoint": "/health",
                "interval": 300,
                "timeout": 60,
                "max_retries": 2,
                "expected_status_code": 200,
                "web_interface": {"enabled": True},
                "slack_integration": {
                    "enabled": True,
                    "webhook_url": "https://hooks.slack.com/your-webhook",
                    "channel": "#health-alerts",
                    "message_template": "🚨 Service {name} is {status} at {timestamp}\nURL: {url}\nError: {error}"
                }
            },
        ]
    }

    with open("debug_config.json", "w") as f:
        json.dump(config, f, indent=2)

    return "debug_config.json"


def demo_config_path_initialization():
    """Demo using config_path parameter (traditional approach)."""
    print("=== Demo 1: Using config_path parameter ===")
    
    # Create test configuration
    config_file = create_test_config()
    print(f"Created test configuration: {config_file}")

    # Create simple status callback
    def status_callback(result):
        status_icon = "[OK]" if result.is_healthy() else "[ERROR]"
        error_info = f" - Error: {result.error_message}" if result.error_message else ""
        print(f"{status_icon} {result.service_name}: {result.status} ({result.response_time * 1000:.1f}ms){error_info}")

    # Initialize health checker using config_path
    print("\nInitializing health checker with config_path...")
    checker = HealthChecker(
        config_path=config_file,
        log_level="INFO"
    )

    # Add status callback and perform quick test
    checker.add_status_callback(status_callback)
    
    print("Performing health checks...")
    results = checker.check_all_services()
    
    print(f"\nChecked {len(results)} services:")
    for name, result in results.items():
        status = "HEALTHY" if result.is_healthy() else "UNHEALTHY"
        print(f"  - {name}: {status}")
    
    checker.stop()
    print("Demo 1 completed.\n")


def demo_direct_config_initialization():
    """Demo using direct config parameter (new approach)."""
    print("=== Demo 2: Using direct config parameter ===")
    
    # Create test configuration
    config_file = create_test_config()
    print(f"Created test configuration: {config_file}")

    # Load config using standalone function
    print("Loading configuration using load_config() function...")
    config = load_config(config_path=config_file)
    print(f"Config loaded successfully, contains {len(config['services'])} service(s)")

    # Create simple status callback
    def status_callback(result):
        status_icon = "[OK]" if result.is_healthy() else "[ERROR]"
        error_info = f" - Error: {result.error_message}" if result.error_message else ""
        print(f"{status_icon} {result.service_name}: {result.status} ({result.response_time * 1000:.1f}ms){error_info}")

    # Initialize health checker using direct config
    print("\nInitializing health checker with direct config...")
    checker = HealthChecker(
        config=config,
        log_level="INFO"
    )

    # Add status callback and perform quick test
    checker.add_status_callback(status_callback)
    
    print("Performing health checks...")
    results = checker.check_all_services()
    
    print(f"\nChecked {len(results)} services:")
    for name, result in results.items():
        status = "HEALTHY" if result.is_healthy() else "UNHEALTHY"
        print(f"  - {name}: {status}")
    
    # checker.stop()
    # print("Demo 2 completed.\n")


def main():
    print("=== Health Checker Core Demo ===")
    print("Demonstrating both initialization patterns\n")

    # Demo 1: Traditional config_path approach
    # demo_config_path_initialization()

    # Demo 2: New direct config approach
    demo_direct_config_initialization()

    print("=== Demo Summary ===")
    # print("[OK] Pattern 1: HealthChecker(config_path='config.json') - Traditional approach")
    print("[OK] Pattern 2: config = load_config('config.json'); HealthChecker(config=config) - New approach")
    print("\nBoth patterns work identically and provide the same functionality.")


if __name__ == "__main__":
    main()
