"""
Formatters for action execution results
"""

from typing import Dict, Any, Optional


def format_action_result_for_ai(action_type: str, result_data: Dict[str, Any], target: Optional[str] = None) -> str:
    """Format action execution results for AI assistant consumption."""
    import logging
    logger = logging.getLogger(__name__)
    logger.info(f"[FORMAT_ACTION] result_data: {result_data}")
    
    success = result_data.get("success", False)
    # Handle None explicitly - .get() returns None if key exists with None value
    message = result_data.get("message") or result_data.get("error") or "No message provided"
    
    # Action type specific formatting
    action_names = {
        "restart_process": "Process Restart",
        "kill_process": "Process Termination", 
        "clear_cache": "Cache Clearing",
        "flush_dns": "DNS Cache Flush",
        "restart_service": "Service Restart"
    }
    
    action_name = action_names.get(action_type, action_type.title())
    target_info = f" ({target})" if target else ""
    
    if success:
        output = f"{action_name} Successful{target_info}\n"
        output += f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
        output += f"Result: {message}\n"
        
        # Add specific metrics if available
        if action_type == "restart_process":
            before_metrics = result_data.get("before", {})
            after_metrics = result_data.get("after", {})
            
            if before_metrics and after_metrics:
                output += f"\nPerformance Impact:\n"
                output += f"• Before: CPU {before_metrics.get('cpu_percent', 0):.1f}%, Memory {before_metrics.get('memory_mb', 0):.0f}MB\n"
                output += f"• After: CPU {after_metrics.get('cpu_percent', 0):.1f}%, Memory {after_metrics.get('memory_mb', 0):.0f}MB"
        
        elif action_type == "clear_cache":
            bytes_freed = result_data.get("bytes_freed", 0)
            files_deleted = result_data.get("files_deleted", 0)
            
            if bytes_freed > 0:
                mb_freed = bytes_freed / (1024 * 1024)
                output += f"\nSpace Freed: {mb_freed:.1f}MB ({files_deleted} files deleted)"
        
        output += f"\n\nNext Steps:\n"
        
        if action_type in ["restart_process", "kill_process"]:
            output += "• Monitor system performance with 'get_device_telemetry'\n"
            output += "• Check if the issue is resolved\n"
            output += "• Verify the application is working properly"
        elif action_type == "clear_cache":
            output += "• Test application performance and startup speed\n"
            output += "• Check if sync/loading issues are resolved"
        elif action_type == "flush_dns":
            output += "• Test website connectivity\n"
            output += "• Try accessing previously problematic sites"
        elif action_type == "restart_service":
            output += "• Verify the service is running properly\n"
            output += "• Test related functionality"
    
    else:
        output = f"{action_name} Failed{target_info}\n"
        output += f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
        output += f"Error: {message}\n"
        
        output += f"\nTroubleshooting:\n"
        
        if "permission" in message.lower() or "access denied" in message.lower():
            output += "• The action requires administrator privileges\n"
            output += "• Verify the AgentNEX agent is running with proper permissions"
        elif "not found" in message.lower():
            output += "• The target process/service may not exist\n"
            output += "• Check the exact name and try again"
        elif "system process" in message.lower() or "blocked" in message.lower():
            output += "• This action is blocked for safety reasons\n"
            output += "• System-critical processes cannot be modified"
        else:
            output += "• Check device connectivity\n"
            output += "• Verify the target exists and is accessible\n"
            output += "• Try again in a few moments"
    
    return output