"""Credential collector command"""

from typing import Dict, Any
from diona.project.cli.commands import CommandModel, CommandParameter
from diona.system.sensitive.credential.windows_credential import WindowsCredentialCollector


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

Collect system credentials from Windows Credential Manager.

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

def execute(args=None) -> str:
    """Execute credential collection
    
    Args:
        args: Command arguments (can be None, dict, or list of strings)
        
    Returns:
        Collection result
    """
    import argparse
    
    # Create argument parser
    parser = argparse.ArgumentParser(description="Collect system credentials from Windows Credential Manager")
    
    # 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
    
    credential = WindowsCredentialCollector()
    
    import json
    
    try:
        result = credential.collect_credentials()
        entries = []
        # Check if result has entries attribute
        if hasattr(result, 'entries'):
            for entry in result.entries:
                # Convert credential entry to serializable dict
                entry_dict = {
                    "target": str(entry.target) if hasattr(entry, 'target') else None,
                    "username": str(entry.username) if hasattr(entry, 'username') else None,
                    "type": str(entry.type) if hasattr(entry, 'type') else None
                }
                entries.append(entry_dict)
            total_entries = len(entries)
        else:
            total_entries = 0
        
        result_data = {
            "summary": f"Collected {total_entries} credentials",
            "details": {
                "entries": entries,
                "total_credentials": total_entries
            },
            "metadata": {
                "source": "Windows Credential Manager"
            }
        }
        return json.dumps(result_data, ensure_ascii=False, indent=2)
    except Exception as e:
        result_data = {
            "summary": f"Error collecting credentials: {str(e)}",
            "details": {},
            "metadata": {
                "error": str(e)
            }
        }
        return json.dumps(result_data, ensure_ascii=False, indent=2)


CredentialCollectorCommand = CommandModel(
    name="collect_credentials",
    description="Collect system credentials",
    implementation=execute,
    parameters=[
        CommandParameter(
            name="help",
            type="bool",
            description="Show help message",
            required=False,
            default=False
        )
    ]
)
