"""File search command"""

from typing import Dict, Any
from diona.project.cli.commands import CommandModel, CommandParameter
from diona.system.sensitive.search.quick_search import QuickSearch
from diona.system.sensitive.search.progressive_search import ProgressiveSearch
from diona.system.sensitive.search.models import SearchConfig


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

Search files for sensitive information such as passwords and API keys.

Options:
  --pattern PATTERN   Search pattern or keyword
  --directory DIR     Directory to search in (default: current directory)
  --type TYPE         Search type: quick, progressive (default: quick)
  --help              Show this help message and exit
        """

def execute(args=None) -> str:
    """Execute file search
    
    Args:
        args: Command arguments (can be None, dict, or list of strings)
        
    Returns:
        Search result
    """
    import argparse
    
    # Create argument parser
    parser = argparse.ArgumentParser(description="Search files for sensitive information such as passwords and API keys")
    parser.add_argument('--pattern', type=str, default='password', help='Search pattern or keyword')
    parser.add_argument('--directory', type=str, default='.', help='Directory to search in (default: current directory)')
    parser.add_argument('--type', type=str, default='quick', choices=['quick', 'progressive'], help='Search type: quick, progressive (default: quick)')
    
    # 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
    
    pattern = parsed_args.pattern
    directory = parsed_args.directory
    search_type = parsed_args.type
    
    import json
    
    try:
        # Create search configuration
        config = SearchConfig(
            target_directory=directory,
            max_files_per_session=1000,
            max_depth=5
        )
        
        # Create search session
        searcher = ProgressiveSearch()
        session_id = searcher.create_search_session(config, task_name="command_search")
        
        # Execute search session
        search_state = searcher.execute_search_session(session_id)
        
        # Get results
        results = searcher.get_search_results(session_id)
        
        # Convert results to serializable format
        serializable_results = []
        for result in results:
            result_dict = {
                "file_path": result.file_path,
                "file_name": result.file_name,
                "file_size": result.file_size,
                "file_extension": result.file_extension,
                "last_modified": result.last_modified.isoformat() if result.last_modified else None,
                "file_type": result.file_type,
                "matched_keywords": result.matched_keywords,
                "risk_score": result.risk_score,
                "confidence": result.confidence,
                "scan_timestamp": result.scan_timestamp.isoformat() if result.scan_timestamp else None
            }
            serializable_results.append(result_dict)
        
        result_data = {
            "summary": f"Found {len(serializable_results)} files matching rules",
            "details": {
                "files": serializable_results,
                "total_files": len(serializable_results)
            },
            "metadata": {
                "pattern": pattern,
                "directory": directory,
                "search_type": search_type
            }
        }
        return json.dumps(result_data, ensure_ascii=False, indent=2)
    except Exception as e:
        result_data = {
            "summary": f"Error searching files: {str(e)}",
            "details": {},
            "metadata": {
                "error": str(e),
                "pattern": pattern,
                "directory": directory,
                "search_type": search_type
            }
        }
        return json.dumps(result_data, ensure_ascii=False, indent=2)


SearchCommand = CommandModel(
    name="search_files",
    description="Search files for sensitive information",
    implementation=execute,
    parameters=[
        CommandParameter(
            name="pattern",
            type="str",
            description="Search pattern or keyword",
            required=False,
            default="password"
        ),
        CommandParameter(
            name="directory",
            type="str",
            description="Directory to search in",
            required=False,
            default="."
        ),
        CommandParameter(
            name="type",
            type="str",
            description="Search type: quick, progressive",
            required=False,
            default="quick"
        ),
        CommandParameter(
            name="help",
            type="bool",
            description="Show help message",
            required=False,
            default=False
        )
    ]
)
