"""Registry analyzer command"""

from typing import Dict, Any
from diona.project.cli.commands import CommandModel, CommandParameter
from diona.system.sensitive.regedit.analyzer import RegistryAnalyzer
from diona.system.sensitive.regedit.recent_docs import RecentDocsAnalyzer
from diona.system.sensitive.regedit.shellbags import ShellBagsAnalyzer


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

Analyze Windows registry for sensitive information.

Options:
  --type TYPE       Analysis type: all, recent_docs, shellbags, general (default: all)
  --help            Show this help message and exit
        """

def execute(args=None) -> str:
    """Execute registry analysis
    
    Args:
        args: Command arguments (can be None, dict, or list of strings)
        
    Returns:
        Analysis result
    """
    import argparse
    
    # Create argument parser
    parser = argparse.ArgumentParser(description="Analyze Windows registry for sensitive information")
    parser.add_argument('--type', type=str, default='all', choices=['all', 'recent_docs', 'shellbags', 'general'], help='Analysis type: all, recent_docs, shellbags, general (default: all)')
    
    # 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
    
    analysis_type = parsed_args.type
    
    import json
    
    result_data = {
        "summary": f"Registry analysis completed (type: {analysis_type})",
        "details": {},
        "metadata": {
            "analysis_type": analysis_type
        }
    }
    
    if analysis_type == 'all' or analysis_type == 'recent_docs':
        try:
            recent_docs_analyzer = RecentDocsAnalyzer()
            recent_docs = recent_docs_analyzer.analyze()
            # Convert recent docs to serializable format
            serializable_docs = []
            for doc in recent_docs:
                if isinstance(doc, dict):
                    serializable_docs.append(doc)
                else:
                    # Convert object to dict
                    try:
                        doc_dict = {}
                        for attr in dir(doc):
                            if not attr.startswith('_'):
                                try:
                                    value = getattr(doc, attr)
                                    if not callable(value):
                                        doc_dict[attr] = str(value) if not isinstance(value, (str, int, float, bool, type(None))) else value
                                except:
                                    pass
                        serializable_docs.append(doc_dict)
                    except:
                        serializable_docs.append(str(doc))
            result_data["details"]["recent_docs"] = {
                "count": len(serializable_docs),
                "documents": serializable_docs
            }
        except Exception as e:
            result_data["details"]["recent_docs_error"] = str(e)
    
    if analysis_type == 'all' or analysis_type == 'shellbags':
        try:
            shellbags_analyzer = ShellBagsAnalyzer()
            shellbags = shellbags_analyzer.analyze()
            # Convert shellbags to serializable format
            serializable_shellbags = []
            for bag in shellbags:
                if isinstance(bag, dict):
                    serializable_shellbags.append(bag)
                else:
                    # Convert object to dict
                    try:
                        bag_dict = {}
                        for attr in dir(bag):
                            if not attr.startswith('_'):
                                try:
                                    value = getattr(bag, attr)
                                    if not callable(value):
                                        bag_dict[attr] = str(value) if not isinstance(value, (str, int, float, bool, type(None))) else value
                                except:
                                    pass
                        serializable_shellbags.append(bag_dict)
                    except:
                        serializable_shellbags.append(str(bag))
            result_data["details"]["shellbags"] = {
                "count": len(serializable_shellbags),
                "shellbags": serializable_shellbags
            }
        except Exception as e:
            result_data["details"]["shellbags_error"] = str(e)
    
    if analysis_type == 'all' or analysis_type == 'general':
        try:
            registry_analyzer = RegistryAnalyzer()
            analysis = registry_analyzer.analyze()
            # Convert analysis to serializable format
            if isinstance(analysis, dict):
                serializable_analysis = analysis
            else:
                # Convert object to dict
                try:
                    serializable_analysis = {}
                    for attr in dir(analysis):
                        if not attr.startswith('_'):
                            try:
                                value = getattr(analysis, attr)
                                if not callable(value):
                                    serializable_analysis[attr] = str(value) if not isinstance(value, (str, int, float, bool, type(None))) else value
                            except:
                                pass
                except:
                    serializable_analysis = str(analysis)
            result_data["details"]["general"] = serializable_analysis
        except Exception as e:
            result_data["details"]["general_error"] = str(e)
    
    return json.dumps(result_data, ensure_ascii=False, indent=2)


RegistryCommand = CommandModel(
    name="analyze_registry",
    description="Analyze registry for sensitive information",
    implementation=execute,
    parameters=[
        CommandParameter(
            name="type",
            type="str",
            description="Analysis type: all, recent_docs, shellbags, general",
            required=False,
            default="all"
        ),
        CommandParameter(
            name="help",
            type="bool",
            description="Show help message",
            required=False,
            default=False
        )
    ]
)
