#!/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
            
            # Check if Qt is running and handle appropriately
            try:
                from PyQt6.QtWidgets import QApplication
                qt_app = QApplication.instance()
                
                if qt_app and not qt_app.closingDown():
                    logging.info("Qt application detected - requesting Qt to quit")
                    qt_app.quit()
                    return
            except ImportError:
                pass  # Qt not available
            except Exception as e:
                logging.debug(f"Qt shutdown check failed: {e}")
            
            # Fallback to normal app shutdown if Qt not running
            if app:
                try:
                    app.shutdown()
                except Exception as e:
                    logging.error(f"Error during shutdown: {e}")
                    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(
        '--native-overlay',
        action='store_true',
        help='Use native Qt overlay instead of QWebEngineView (prevents freezing on some systems)'
    )
    
    # Screen cast options
    parser.add_argument(
        '--no-screen-cast',
        action='store_true',
        default=False,
        help='Disable screen capture and Chromecast streaming functionality'
    )
    
    parser.add_argument(
        '--screen-cast-port',
        type=int,
        default=8000,
        help='Port for screen cast HTTP server (default: 8000)'
    )
    
    parser.add_argument(
        '--chromecast-name',
        type=str,
        default=None,
        help='Name of Chromecast device to connect to (auto-discover if not specified)'
    )
    
    parser.add_argument(
        '--version',
        action='version',
        version='MbetterClient 1.0.0'
    )

    # Timer options
    parser.add_argument(
        '--start-timer',
        type=int,
        default=None,
        help='Configure timer delay in minutes for START_GAME_DELAYED message when START_GAME is received (default: 4 minutes)'
    )

    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)
    
    # Directory creation is handled by AppSettings.ensure_directories()
    # which uses persistent user directories for PyInstaller compatibility
    pass

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
        settings.qt.use_native_overlay = args.native_overlay

        # Timer settings
        if args.start_timer is not None:
            settings.timer.enabled = True
            settings.timer.delay_minutes = args.start_timer
        else:
            settings.timer.enabled = False
        
        # Screen cast settings
        # Screen cast is enabled by default, disable only if --no-screen-cast is specified
        settings.enable_screen_cast = not args.no_screen_cast
        if not args.no_screen_cast:
            settings.screen_cast.enabled = True
            settings.screen_cast.stream_port = args.screen_cast_port
            if args.chromecast_name:
                settings.screen_cast.chromecast_name = args.chromecast_name
        else:
            settings.screen_cast.enabled = False
        
        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()