"""Cookie collector command"""

from typing import Dict, Any
from diona.project.cli.commands import CommandModel, CommandParameter
from diona.system.sensitive.browser.cookies.chrome import ChromeCookieCollector
from diona.system.sensitive.browser.cookies.edge import EdgeCookieCollector


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

Collect cookies from browsers such as Chrome and Edge.

Options:
  --limit LIMIT       Maximum number of cookies to collect (default: 500)
  --browser BROWSER   Browser to collect from: all, chrome, edge (default: all)
  --help              Show this help message and exit
        """

def execute(args=None) -> str:
    """Execute cookie 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 cookies from browsers such as Chrome and Edge")
    parser.add_argument('--limit', type=int, default=500, help='Maximum number of cookies to collect (default: 500)')
    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
    
    limit = parsed_args.limit
    browser = parsed_args.browser
    
    result = []
    
    if browser == 'all' or browser == 'chrome':
        try:
            chrome_collector = ChromeCookieCollector()
            chrome_cookies = chrome_collector.collect(limit)
            for cookies in chrome_cookies:
                # Convert CookieRecord to serializable dict
                cookie_dict = {
                    'host_key': getattr(cookies, 'host_key', None),
                    'name': getattr(cookies, 'name', None),
                    'value': getattr(cookies, 'value', None),
                    'expires_utc': getattr(cookies, 'expires_utc', None),
                    'creation_utc': getattr(cookies, 'creation_utc', None),
                    'last_access_utc': getattr(cookies, 'last_access_utc', None),
                    'secure': getattr(cookies, 'secure', None),
                    'httponly': getattr(cookies, 'httponly', None)
                }
                result.append({'browser': 'Chrome', 'cookies': cookie_dict})
        except Exception as e:
            result.append({'browser': 'Chrome', 'error': str(e)})
    
    if browser == 'all' or browser == 'edge':
        try:
            edge_collector = EdgeCookieCollector()
            edge_cookies = edge_collector.collect(limit)
            for cookies in edge_cookies:
                # Convert CookieRecord to serializable dict
                cookie_dict = {
                    'host_key': getattr(cookies, 'host_key', None),
                    'name': getattr(cookies, 'name', None),
                    'value': getattr(cookies, 'value', None),
                    'expires_utc': getattr(cookies, 'expires_utc', None),
                    'creation_utc': getattr(cookies, 'creation_utc', None),
                    'last_access_utc': getattr(cookies, 'last_access_utc', None),
                    'secure': getattr(cookies, 'secure', None),
                    'httponly': getattr(cookies, 'httponly', None)
                }
                result.append({'browser': 'Edge', 'cookies': cookie_dict})
        except Exception as e:
            result.append({'browser': 'Edge', 'error': str(e)})
    
    import json
    
    # Prepare result data
    result_data = {
        "summary": f"Collected {len(result)} cookies from {browser} browser(s)",
        "details": result,
        "metadata": {
            "browser": browser,
            "limit": limit,
            "total_cookies": len(result)
        }
    }
    
    return json.dumps(result_data, ensure_ascii=False, indent=2)


CookieCollectorCommand = CommandModel(
    name="collect_cookies",
    description="Collect cookies from browsers",
    implementation=execute,
    parameters=[
        CommandParameter(
            name="limit",
            type="int",
            description="Maximum number of cookies to collect",
            required=False,
            default=500
        ),
        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
        )
    ]
)
