"""Sensitive file analyzer command"""

import os
from typing import Dict, Any, List
from diona.project.cli.commands import CommandModel, CommandParameter
from diona.system.sensitive.sensitivefile.file_analyzer import FileAnalyzer
from diona.system.sensitive.sensitivefile.config_analyzer import ConfigFileAnalyzer


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

Analyze files for sensitive information such as passwords, API keys, etc.

Options:
  --type TYPE         Analysis type: all, files, configs (default: all)
  --files FILES       Comma-separated list of file paths to analyze
  --directory DIR     Directory to scan for files (default: current directory)
  --help              Show this help message and exit
        """

def execute(args=None) -> str:
    """Execute file 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 files for sensitive information such as passwords, API keys, etc.")
    parser.add_argument('--type', type=str, default='all', choices=['all', 'files', 'configs'], help='Analysis type: all, files, configs (default: all)')
    parser.add_argument('--files', type=str, default='', help='Comma-separated list of file paths to analyze')
    parser.add_argument('--directory', type=str, default='.', help='Directory to scan for files (default: current directory)')
    
    # 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
    directory = parsed_args.directory
    files = parsed_args.files
    
    # Validate input
    if not files and not directory:
        return get_help()
    
    # Process file paths
    file_paths = []
    if files:
        file_paths = [f.strip() for f in files.split(',')]
    else:
        # If no files specified, scan directory
        for root, _, filenames in os.walk(directory):
            for filename in filenames:
                file_paths.append(os.path.join(root, filename))
    
    import json
    
    result_data = {
        "summary": f"File analysis completed (type: {analysis_type})",
        "details": {},
        "metadata": {
            "analysis_type": analysis_type,
            "file_count": len(file_paths),
            "target": files if files else directory
        }
    }
    
    if analysis_type == 'all' or analysis_type == 'files':
        try:
            file_analyzer = FileAnalyzer()
            analysis_result = file_analyzer.analyze_files(file_paths)
            # Convert analysis_result to serializable format
            if hasattr(analysis_result, 'total_files'):
                total_files = analysis_result.total_files
            else:
                total_files = 0
            
            # Convert results to serializable format
            if hasattr(analysis_result, 'results'):
                serializable_results = []
                for result in analysis_result.results:
                    if isinstance(result, dict):
                        serializable_results.append(result)
                    else:
                        # Convert object to dict
                        try:
                            result_dict = {}
                            for attr in dir(result):
                                if not attr.startswith('_'):
                                    try:
                                        value = getattr(result, attr)
                                        if not callable(value):
                                            result_dict[attr] = str(value) if not isinstance(value, (str, int, float, bool, type(None))) else value
                                    except:
                                        pass
                            serializable_results.append(result_dict)
                        except:
                            serializable_results.append(str(result))
            else:
                serializable_results = []
            
            result_data["details"]["file_analysis"] = {
                "total_files": total_files,
                "results": serializable_results
            }
        except Exception as e:
            result_data["details"]["file_analysis_error"] = str(e)
    
    if analysis_type == 'all' or analysis_type == 'configs':
        try:
            config_analyzer = ConfigFileAnalyzer()
            configs = config_analyzer.analyze_files(file_paths)
            # Convert configs to serializable format
            serializable_configs = []
            for config in configs:
                if isinstance(config, dict):
                    serializable_configs.append(config)
                else:
                    # Convert object to dict
                    try:
                        config_dict = {}
                        for attr in dir(config):
                            if not attr.startswith('_'):
                                try:
                                    value = getattr(config, attr)
                                    if not callable(value):
                                        config_dict[attr] = str(value) if not isinstance(value, (str, int, float, bool, type(None))) else value
                                except:
                                    pass
                        serializable_configs.append(config_dict)
                    except:
                        serializable_configs.append(str(config))
            
            result_data["details"]["config_analysis"] = {
                "total_configs": len(serializable_configs),
                "configs": serializable_configs
            }
        except Exception as e:
            result_data["details"]["config_analysis_error"] = str(e)
    
    return json.dumps(result_data, ensure_ascii=False, indent=2)


SensitiveFileCommand = CommandModel(
    name="analyze_files",
    description="Analyze files for sensitive information",
    implementation=execute,
    parameters=[
        CommandParameter(
            name="type",
            type="str",
            description="Analysis type: all, files, configs",
            required=False,
            default="all"
        ),
        CommandParameter(
            name="files",
            type="str",
            description="Comma-separated list of file paths to analyze",
            required=False,
            default=""
        ),
        CommandParameter(
            name="directory",
            type="str",
            description="Directory to scan for files",
            required=False,
            default="."
        ),
        CommandParameter(
            name="help",
            type="bool",
            description="Show help message",
            required=False,
            default=False
        )
    ]
)
