"""Run context command"""

from typing import Dict, Any
from diona.project.cli.commands import CommandModel, CommandParameter
from diona.system.sensitive.runcontext.context import RunContext


def get_help() -> str:
    """Get help information for the command"""
    return """
Usage: run_context [OPTIONS]

Get run context information including processes and network connections.

Options:
  --help            Show this help message and exit
        """

def execute(args=None) -> str:
    """Execute run context collection
    
    Args:
        args: Command arguments (can be None, dict, or list of strings)
        
    Returns:
        Run context information
    """
    import argparse
    
    # Create argument parser
    parser = argparse.ArgumentParser(description="Get run context information including processes and network connections")
    
    # Parse arguments
    if args is None:
        # No arguments provided
        parsed_args = parser.parse_args([])
    elif isinstance(args, list):
        # List of strings (command line arguments)
        try:
            parsed_args = parser.parse_args(args)
        except SystemExit:
            return get_help()
    elif isinstance(args, dict):
        # Dict of arguments
        parsed_args = argparse.Namespace(**args)
    else:
        # Invalid argument type
        return get_help()
    
    # help is handled by argparse automatically
    
    context = RunContext()
    
    import json
    
    try:
        context_info = context.get_context_info()
        # Convert context_info to serializable format
        if isinstance(context_info, dict):
            serializable_context = context_info
        else:
            # Convert object to dict
            try:
                serializable_context = {}
                for attr in dir(context_info):
                    if not attr.startswith('_'):
                        try:
                            value = getattr(context_info, attr)
                            if not callable(value):
                                # Handle nested objects
                                if hasattr(value, '__dict__') and not isinstance(value, (str, int, float, bool, type(None), list, dict)):
                                    nested_dict = {}
                                    for nested_attr in dir(value):
                                        if not nested_attr.startswith('_'):
                                            try:
                                                nested_value = getattr(value, nested_attr)
                                                if not callable(nested_value):
                                                    nested_dict[nested_attr] = str(nested_value) if not isinstance(nested_value, (str, int, float, bool, type(None))) else nested_value
                                            except:
                                                pass
                                    serializable_context[attr] = nested_dict
                                elif isinstance(value, list):
                                    # Handle lists
                                    serializable_list = []
                                    for item in value:
                                        if isinstance(item, dict):
                                            serializable_list.append(item)
                                        elif hasattr(item, '__dict__'):
                                            # Convert list items to dict
                                            item_dict = {}
                                            for item_attr in dir(item):
                                                if not item_attr.startswith('_'):
                                                    try:
                                                        item_value = getattr(item, item_attr)
                                                        if not callable(item_value):
                                                            item_dict[item_attr] = str(item_value) if not isinstance(item_value, (str, int, float, bool, type(None))) else item_value
                                                    except:
                                                        pass
                                            serializable_list.append(item_dict)
                                        else:
                                            serializable_list.append(str(item) if not isinstance(item, (str, int, float, bool, type(None))) else item)
                                    serializable_context[attr] = serializable_list
                                else:
                                    serializable_context[attr] = str(value) if not isinstance(value, (str, int, float, bool, type(None))) else value
                        except:
                            pass
            except:
                serializable_context = str(context_info)
        
        result_data = {
            "summary": "Run context collected successfully",
            "details": {
                "context": serializable_context
            },
            "metadata": {
                "source": "RunContext"
            }
        }
        return json.dumps(result_data, ensure_ascii=False, indent=2)
    except Exception as e:
        result_data = {
            "summary": f"Error getting run context: {str(e)}",
            "details": {},
            "metadata": {
                "error": str(e)
            }
        }
        return json.dumps(result_data, ensure_ascii=False, indent=2)


RunContextCommand = CommandModel(
    name="run_context",
    description="Get run context information",
    implementation=execute,
    parameters=[
        CommandParameter(
            name="help",
            type="bool",
            description="Show help message",
            required=False,
            default=False
        )
    ]
)
