#!/usr/bin/env python3
"""
MbetterClient - Cross-platform multimedia client application
Entry point for the application with command line argument handling
"""

import sys
import os
import argparse
import signal
import logging
from pathlib import Path

# Add the project root to Python path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from mbetterclient.core.application import MbetterClientApplication
from mbetterclient.utils.logger import setup_logging
from mbetterclient.config.settings import AppSettings

def setup_signal_handlers(app):
    """Setup signal handlers for graceful shutdown"""
    # Use a mutable object to track shutdown state
    shutdown_state = {'requested': False}
    
    def signal_handler(signum, frame):
        if not shutdown_state['requested']:
            logging.info("Received signal {}, initiating graceful shutdown...".format(signum))
            shutdown_state['requested'] = True
            if app:
                try:
                    app.shutdown()
                    # Don't call sys.exit() here - let the app.run() method handle the exit
                    # The shutdown_event.set() in app.shutdown() will wake up the main thread
                except Exception as e:
                    logging.error(f"Error during shutdown: {e}")
                    # Only force exit if shutdown fails
                    sys.exit(1)
            else:
                sys.exit(0)
        else:
            logging.warning("Second shutdown signal received, forcing immediate exit...")
            sys.exit(1)
    
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    # Windows doesn't have SIGHUP
    if hasattr(signal, 'SIGHUP'):
        signal.signal(signal.SIGHUP, signal_handler)

def parse_arguments():
    """Parse command line arguments"""
    parser = argparse.ArgumentParser(
        description='MbetterClient - Cross-platform multimedia client',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python main.py                    # Run in fullscreen mode
  python main.py --no-fullscreen    # Run in windowed mode
  python main.py --web-port 8080    # Custom web dashboard port
  python main.py --debug            # Enable debug logging
        """
    )
    
    # Display options
    parser.add_argument(
        '--no-fullscreen',
        action='store_true',
        help='Run video player in windowed mode instead of fullscreen'
    )
    
    parser.add_argument(
        '--web-port',
        type=int,
        default=5001,
        help='Port for web dashboard (default: 5001)'
    )
    
    parser.add_argument(
        '--web-host',
        type=str,
        default='127.0.0.1',
        help='Host for web dashboard (default: 127.0.0.1)'
    )
    
    # Database options
    parser.add_argument(
        '--db-path',
        type=str,
        default=None,
        help='Custom database file path (default: data/mbetterclient.db)'
    )
    
    # Logging options
    parser.add_argument(
        '--debug',
        action='store_true',
        help='Enable debug logging'
    )
    
    parser.add_argument(
        '--log-file',
        type=str,
        default=None,
        help='Log file path (default: logs/mbetterclient.log)'
    )
    
    # Development options
    parser.add_argument(
        '--dev-mode',
        action='store_true',
        help='Enable development mode with additional debugging'
    )
    
    parser.add_argument(
        '--no-qt',
        action='store_true',
        help='Disable PyQt interface (web dashboard only)'
    )
    
    parser.add_argument(
        '--no-web',
        action='store_true',
        help='Disable web dashboard (PyQt interface only)'
    )
    
    parser.add_argument(
        '--version',
        action='version',
        version='MbetterClient 1.0.0'
    )
    
    return parser.parse_args()

def validate_arguments(args):
    """Validate command line arguments"""
    if args.no_qt and args.no_web:
        print("Error: Cannot disable both Qt and web interfaces")
        sys.exit(1)
    
    if args.web_port < 1 or args.web_port > 65535:
        print("Error: Web port must be between 1 and 65535")
        sys.exit(1)
    
    # Create necessary directories
    project_root = Path(__file__).parent
    
    # Data directory
    data_dir = project_root / 'data'
    data_dir.mkdir(exist_ok=True)
    
    # Logs directory
    logs_dir = project_root / 'logs'
    logs_dir.mkdir(exist_ok=True)
    
    # Assets directory
    assets_dir = project_root / 'assets'
    assets_dir.mkdir(exist_ok=True)
    
    # Templates directory
    templates_dir = project_root / 'templates'
    templates_dir.mkdir(exist_ok=True)

def main():
    """Main entry point"""
    try:
        # Parse command line arguments
        args = parse_arguments()
        
        # Validate arguments and create directories
        validate_arguments(args)
        
        # Setup logging
        log_level = logging.DEBUG if args.debug else logging.INFO
        log_file = args.log_file or 'logs/mbetterclient.log'
        logger = setup_logging(level=log_level, log_file=log_file)
        
        logger.info("=" * 60)
        logger.info("MbetterClient Starting")
        logger.info("=" * 60)
        logger.info(f"Arguments: {vars(args)}")
        
        # Create application settings
        settings = AppSettings()
        settings.fullscreen = not args.no_fullscreen
        settings.web_host = args.web_host
        settings.web_port = args.web_port
        settings.debug_mode = args.debug or args.dev_mode
        settings.enable_qt = not args.no_qt
        settings.enable_web = not args.no_web
        
        if args.db_path:
            settings.database_path = args.db_path
        
        # Create and initialize application
        app = MbetterClientApplication(settings)
        
        # Setup signal handlers for graceful shutdown
        setup_signal_handlers(app)
        
        # Initialize application
        logger.info("Initializing application components...")
        if not app.initialize():
            logger.error("Failed to initialize application")
            sys.exit(1)
        
        logger.info("Starting application...")
        # Run the application (this blocks until shutdown)
        exit_code = app.run()
        
        logger.info("Application finished")
        sys.exit(exit_code)
        
    except KeyboardInterrupt:
        print("\nInterrupted by user")
        sys.exit(0)
    except Exception as e:
        print(f"Fatal error: {e}")
        if args.debug if 'args' in locals() else False:
            import traceback
            traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    main()