"""
Command-line interface for health checker.
"""

import argparse
import signal
import logging
import sys
from pathlib import Path
from typing import NoReturn, Optional
import types

from .client import HealthChecker
from .core.config import ConfigValidator
from .core.checker import HealthCheckResult

logger = logging.getLogger(__name__)


def signal_handler(signum: int, frame: types.FrameType) -> NoReturn:
    """
    Handle shutdown signals gracefully.
    
    Args:
        signum: Signal number
        frame: Current stack frame
    """
    print("\nShutting down health checker...")
    sys.exit(0)


def create_sample_config(output_path: str = "config.json") -> None:
    """
    Create a sample configuration file.
    
    Args:
        output_path: Path where to save the sample config
    """
    validator = ConfigValidator()
    config = validator.get_default_config()
    
    import json
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(config, f, indent=2, ensure_ascii=False)
    
    print(f"Sample configuration created at: {output_path}")


def validate_config(config_path: str) -> None:
    """
    Validate a configuration file.
    
    Args:
        config_path: Path to configuration file
    """
    try:
        validator = ConfigValidator()
        config: dict = validator.load_config(config_path)
        print(f"✅ Configuration file '{config_path}' is valid!")
        print(f"📊 Found {len(config['services'])} service(s) configured")
        
        for service in config['services']:
            status: str = "🟢" if service.get('email_alert', {}).get('enabled') else "🔴"
            status += "📧 " if service.get('email_alert', {}).get('enabled') else ""
            status += "💬 " if service.get('slack_integration', {}).get('enabled') else ""
            status += "🌐 " if service.get('web_interface', {}).get('enabled') else ""
            print(f"  {service['name']}: {status}")
            
    except Exception as e:
        print(f"❌ Configuration validation failed: {e}")
        sys.exit(1)


def main() -> None:
    """
    Main CLI entry point.
    
    Raises:
        SystemExit: When the program should exit
    """
    parser: argparse.ArgumentParser = argparse.ArgumentParser(
        prog="openhealth",
        description="A comprehensive health monitoring tool for backend and frontend services",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  openhealth start                    # Start with default config.json
  openhealth start -c my_config.json  # Start with custom config
  openhealth validate-config          # Validate configuration
  openhealth create-config            # Create sample config
        """
    )
    
    subparsers = parser.add_subparsers(dest='command', help='Available commands')
    
    # Start command
    start_parser = subparsers.add_parser('start', help='Start health monitoring')
    start_parser.add_argument(
        '-c', '--config',
        default='app.json',
        help='Configuration file path (default: app.json)'
    )
    start_parser.add_argument(
        '-l', '--log-level',
        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
        default='INFO',
        help='Logging level (default: INFO)'
    )
    start_parser.add_argument(
        '--log-file',
        help='Log file path (optional)'
    )
    start_parser.add_argument(
        '--daemon',
        action='store_true',
        help='Run in daemon mode (background)'
    )
    
    # Validate config command
    validate_parser = subparsers.add_parser('validate-config', help='Validate configuration file')
    validate_parser.add_argument(
        '-c', '--config',
        default='app.json',
        help='Configuration file path (default: app.json)'
    )
    
    # Create config command
    create_parser = subparsers.add_parser('create-config', help='Create sample configuration file')
    create_parser.add_argument(
        '-o', '--output',
        default='config.json',
        help='Output file path (default: config.json)'
    )
    
    # Status command
    status_parser = subparsers.add_parser('status', help='Check service status')
    status_parser.add_argument(
        '-c', '--config',
        default='app.json',
        help='Configuration file path (default: app.json)'
    )
    status_parser.add_argument(
        '--service',
        help='Check specific service only'
    )
    
    # Parse arguments
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        sys.exit(1)
    
    # Setup signal handlers
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    try:
        if args.command == 'start':
            # Start monitoring
            print(f"🚀 Starting health checker with config: {args.config}")
            
            checker: HealthChecker = HealthChecker(
                config_path=args.config,
                log_level=args.log_level,
                log_file=args.log_file
            )
            
            # Custom status callback
            def status_callback(result: HealthCheckResult) -> None:
                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)")
            
            checker.add_status_callback(status_callback)
            
            if args.daemon:
                print("🔄 Running in daemon mode...")
                # In daemon mode, we just let it run
                checker.start()
                try:
                    import time
                    while True:
                        time.sleep(1)
                except KeyboardInterrupt:
                    pass
            else:
                print("🔄 Starting monitoring (Press Ctrl+C to stop)...")
                checker.start()
                try:
                    import time
                    while True:
                        time.sleep(1)
                except KeyboardInterrupt:
                    pass
            
            checker.stop()
            
        elif args.command == 'validate-config':
            validate_config(args.config)
            
        elif args.command == 'create-config':
            create_sample_config(args.output)
            
        elif args.command == 'status':
            # Check current status
            checker: HealthChecker = HealthChecker(config_path=args.config)
            
            if args.service:
                result: Optional[HealthCheckResult] = checker.check_service(args.service)
                if result:
                    status_icon = "✅" if result.is_healthy() else "⚠️" if result.status == 'unhealthy' else "🚨"
                    print(f"{status_icon} {result.service_name}: {result.status}")
                    print(f"   URL: {result.url}")
                    print(f"   Response Time: {result.response_time * 1000:.1f}ms")
                    print(f"   Timestamp: {result.timestamp}")
                    if result.error_message:
                        print(f"   Error: {result.error_message}")
                else:
                    print(f"❌ Service '{args.service}' not found")
            else:
                results: dict[str, HealthCheckResult] = checker.check_all_services()
                print(f"📊 Status of {len(results)} service(s):")
                for name, result in results.items():
                    status_icon = "✅" if result.is_healthy() else "⚠️" if result.status == 'unhealthy' else "🚨"
                    print(f"{status_icon} {name}: {result.status} ({result.response_time * 1000:.1f}ms)")
        
    except KeyboardInterrupt:
        print("\n👋 Goodbye!")
        sys.exit(0)
    except Exception as e:
        print(f"❌ Error: {e}")
        sys.exit(1)


if __name__ == '__main__':
    main()