"""Clipboard command"""

from typing import Dict, Any
from diona.project.cli.commands import CommandModel, CommandParameter
from diona.system.sensitive.clipboard.windows_clipboard import WindowsClipboardMonitor


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

Get or monitor clipboard content.

Options:
  --operation OPERATION   Operation to perform: get, monitor (default: get)
  --duration DURATION     Duration in seconds for monitoring (default: 10)
  --help                  Show this help message and exit
        """

def execute(args=None) -> str:
    """Execute clipboard operation
    
    Args:
        args: Command arguments (can be None, dict, or list of strings)
        
    Returns:
        Clipboard content
    """
    import argparse
    
    # Create argument parser
    parser = argparse.ArgumentParser(description="Get or monitor clipboard content")
    parser.add_argument('--operation', type=str, default='get', choices=['get', 'monitor'], help='Operation to perform: get, monitor (default: get)')
    parser.add_argument('--duration', type=int, default=10, help='Duration in seconds for monitoring (default: 10)')
    
    # 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
    
    operation = parsed_args.operation
    
    clipboard = WindowsClipboardMonitor()
    
    import json
    
    if operation == 'get':
        try:
            # Use monitor_clipboard method with short duration
            result = clipboard.monitor_clipboard(duration=1, interval=0.1)
            if hasattr(result, 'entries') and result.entries:
                entry = result.entries[-1]
                # Get content safely
                content = ""
                if hasattr(entry, 'content'):
                    if hasattr(entry.content, 'text'):
                        content = entry.content.text if entry.content.text else "Empty"
                    else:
                        content = str(entry.content)
                else:
                    content = "Empty"
                
                # Get timestamp safely
                timestamp = None
                if hasattr(entry, 'timestamp'):
                    try:
                        timestamp = entry.timestamp.isoformat()
                    except:
                        timestamp = str(entry.timestamp)
                
                result_data = {
                    "summary": f"Clipboard content: {content}",
                    "details": {
                        "content": content,
                        "timestamp": timestamp
                    },
                    "metadata": {
                        "operation": operation,
                        "has_content": True
                    }
                }
            else:
                result_data = {
                    "summary": "Clipboard is empty",
                    "details": {},
                    "metadata": {
                        "operation": operation,
                        "has_content": False
                    }
                }
            return json.dumps(result_data, ensure_ascii=False, indent=2)
        except Exception as e:
            result_data = {
                "summary": f"Error getting clipboard content: {str(e)}",
                "details": {},
                "metadata": {
                    "operation": operation,
                    "error": str(e)
                }
            }
            return json.dumps(result_data, ensure_ascii=False, indent=2)
    elif operation == 'monitor':
        try:
            duration = parsed_args.duration
            result = clipboard.monitor_clipboard(duration=duration, interval=1.0)
            entries = []
            if hasattr(result, 'entries'):
                for entry in result.entries:
                    # Get content safely
                    content = ""
                    if hasattr(entry, 'content'):
                        if hasattr(entry.content, 'text'):
                            content = entry.content.text if entry.content.text else "Empty"
                        else:
                            content = str(entry.content)
                    else:
                        content = "Empty"
                    
                    # Get timestamp safely
                    timestamp = None
                    if hasattr(entry, 'timestamp'):
                        try:
                            timestamp = entry.timestamp.isoformat()
                        except:
                            timestamp = str(entry.timestamp)
                    
                    entries.append({
                        "content": content,
                        "timestamp": timestamp
                    })
            
            result_data = {
                "summary": f"Monitored clipboard for {duration} seconds, found {len(entries)} entries",
                "details": {
                    "entries": entries,
                    "total_entries": len(entries)
                },
                "metadata": {
                    "operation": operation,
                    "duration": duration
                }
            }
            return json.dumps(result_data, ensure_ascii=False, indent=2)
        except Exception as e:
            result_data = {
                "summary": f"Error monitoring clipboard: {str(e)}",
                "details": {},
                "metadata": {
                    "operation": operation,
                    "error": str(e)
                }
            }
            return json.dumps(result_data, ensure_ascii=False, indent=2)
    else:
        return get_help()


ClipboardCommand = CommandModel(
    name="clipboard",
    description="Get clipboard content",
    implementation=execute,
    parameters=[
        CommandParameter(
            name="operation",
            type="str",
            description="Operation to perform: get, monitor",
            required=False,
            default="get"
        ),
        CommandParameter(
            name="duration",
            type="int",
            description="Duration in seconds for monitoring",
            required=False,
            default=10
        ),
        CommandParameter(
            name="help",
            type="bool",
            description="Show help message",
            required=False,
            default=False
        )
    ]
)
