#!/usr/bin/python3
import platform
import os
import subprocess
from .logger import get_logger

logger = get_logger(__name__)

def handle_integration(args):
    if platform.system() == 'Windows':
        from .integration_windows import WindowsClassicContextMenuIntegration as ContextMenuIntegration
        if args.install_integration:
            success = ContextMenuIntegration.install()
            if success:
                logger.info("Integration installed successfully.")
                return True
            else:
                logger.error("Integration installation failed.")
                return False
        elif args.uninstall_integration:
            success = ContextMenuIntegration.uninstall()
            if success:
                logger.info("Integration uninstalled successfully.")
                return True
            else:
                logger.error("Integration uninstallation failed.")
                return False
    #elif platform.system() == 'Darwin':
    #    from .integration_macos import MacOSContextMenuIntegration as ContextMenuIntegration
    #    if args.install_integration:
    #        success = ContextMenuIntegration.install()
    #        if success:
    #            logger.info("Integration installed successfully.")
    #            return True
    #        else:
    #            logger.error("Integration installation failed.")
    #            return False
    #    elif args.uninstall_integration:
    #        success = ContextMenuIntegration.uninstall()
    #        if success:
    #            logger.info("Integration uninstalled successfully.")
    #            return True
    #        else:
    #            logger.error("Integration uninstallation failed.")
    #            return False
    elif platform.system() == 'Darwin':
        raise NotImplementedError("Context menu integration is not supported on MacOS YET. But Soon™")
    elif platform.system() == 'Linux':
        # Check if we're running in KDE
        kde_session = os.environ.get('KDE_SESSION_VERSION') or os.environ.get('KDE_FULL_SESSION')
        desktop_session = os.environ.get('DESKTOP_SESSION', '').lower()
        xdg_current_desktop = os.environ.get('XDG_CURRENT_DESKTOP', '').lower()
        
        if kde_session or 'kde' in desktop_session or 'kde' in xdg_current_desktop:
            from .integration_kde import KDEServiceMenuIntegration as ContextMenuIntegration
            if args.install_integration:
                success = ContextMenuIntegration.install()
                if success:
                    logger.info("Integration installed successfully.")
                    return True
                else:
                    logger.error("Integration installation failed.")
                    return False
            elif args.uninstall_integration:
                success = ContextMenuIntegration.uninstall()
                if success:
                    logger.info("Integration uninstalled successfully.")
                    return True
                else:
                    logger.error("Integration uninstallation failed.")
                    return False
        else:
            raise NotImplementedError("Context menu integration is currently only supported on KDE. Other Linux desktop environments are not supported yet.")
    else:
        raise NotImplementedError(f"Context menu integration is not supported on this OS: {platform.system()}")
    
def handle_config():
    """Opens the configuration file in the default text editor."""
    config_path = os.path.join(os.path.expanduser("~"), ".tonietoolbox", "config.json")
    if not os.path.exists(config_path):
        logger.info(f"Configuration file not found at {config_path}.")
        logger.info("Creating a new configuration file. Using --install-integration will create a new config file.")
        return
    if platform.system() == "Windows":
        from .integration_windows import WindowsClassicContextMenuIntegration as ContextMenuIntegration
        context_menu = ContextMenuIntegration()
        context_menu._apply_config_template()
        os.startfile(config_path)
    elif platform.system() == "Darwin":
        from .integration_macos import MacOSContextMenuIntegration as ContextMenuIntegration
        context_menu = ContextMenuIntegration()
        context_menu._apply_config_template()
        subprocess.call(["open", config_path])
    elif platform.system() == "Linux":
        kde_session = os.environ.get('KDE_SESSION_VERSION') or os.environ.get('KDE_FULL_SESSION')
        desktop_session = os.environ.get('DESKTOP_SESSION', '').lower()
        xdg_current_desktop = os.environ.get('XDG_CURRENT_DESKTOP', '').lower()
        
        if kde_session or 'kde' in desktop_session or 'kde' in xdg_current_desktop:
            try:
                from .integration_kde import KDEServiceMenuIntegration as ContextMenuIntegration
                context_menu = ContextMenuIntegration()
                context_menu._apply_config_template()
            except Exception as e:
                logger.warning(f"Could not create config template: {e}")
        
        subprocess.call(["xdg-open", config_path])
    else:
        logger.error(f"Unsupported OS: {platform.system()}")