"""
Action tools for device management and system operations
"""

from typing import Any, Dict, Optional

from app.tools.base import BaseTool
from app.client.backend_client import BackendClient
from app.formatters.action_formatter import format_action_result_for_ai


class RestartProcessTool(BaseTool):
    """Tool to restart application processes"""
    
    @property
    def name(self) -> str:
        return "restart_process"
    
    @property
    def description(self) -> str:
        return ("Restart a specific application process on a device. "
                "Safe for browsers and office applications. "
                "Use when diagnosis shows high memory/CPU usage from one application. "
                "Blocks system processes for safety.")
    
    @property
    def input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "device_id": {
                    "type": "string",
                    "description": "The UUID of the device"
                },
                "process_name": {
                    "type": "string",
                    "description": "Name of the process to restart (e.g., 'chrome.exe', 'outlook.exe')"
                }
            },
            "required": ["device_id", "process_name"]
        }
    
    async def execute(self, arguments: Dict[str, Any], backend_client: Optional[BackendClient] = None) -> str:
        """Execute process restart"""
        client = self.get_client(backend_client)
        device_id = arguments["device_id"]
        process_name = arguments["process_name"]
        
        action_data = {
            "type": "restart_process",
            "process_name": process_name
        }
        result = await client.execute_action(device_id, action_data)
        
        # Format action result for AI consumption
        return format_action_result_for_ai("restart_process", result, process_name)


class KillProcessTool(BaseTool):
    """Tool to force-close processes"""
    
    @property
    def name(self) -> str:
        return "kill_process"
    
    @property
    def description(self) -> str:
        return ("Force-close a process on a device. "
                "Use only for completely frozen applications when restart is not possible. "
                "Can use process name or PID. Blocks critical system processes for safety.")
    
    @property
    def input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "device_id": {
                    "type": "string",
                    "description": "The UUID of the device"
                },
                "identifier": {
                    "type": "string",
                    "description": "Process name (e.g., 'chrome.exe') or PID number to kill"
                }
            },
            "required": ["device_id", "identifier"]
        }
    
    async def execute(self, arguments: Dict[str, Any], backend_client: Optional[BackendClient] = None) -> str:
        """Execute process kill"""
        client = self.get_client(backend_client)
        device_id = arguments["device_id"]
        identifier = arguments["identifier"]
        
        action_data = {
            "type": "kill_process",
            "identifier": identifier
        }
        result = await client.execute_action(device_id, action_data)
        
        # Format action result for AI consumption
        return format_action_result_for_ai("kill_process", result, identifier)


class ClearCacheTool(BaseTool):
    """Tool to clear application cache"""
    
    @property
    def name(self) -> str:
        return "clear_cache"
    
    @property
    def description(self) -> str:
        return ("Clear cache files for popular applications. "
                "Use when diagnosis points to corrupted cache causing slow startup or sync issues. "
                "Supported applications: outlook, chrome, teams, edge. "
                "Reports bytes freed and files deleted.")
    
    @property
    def input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "device_id": {
                    "type": "string",
                    "description": "The UUID of the device"
                },
                "application": {
                    "type": "string",
                    "enum": ["outlook", "chrome", "teams", "edge"],
                    "description": "Application to clear cache for"
                }
            },
            "required": ["device_id", "application"]
        }
    
    async def execute(self, arguments: Dict[str, Any], backend_client: Optional[BackendClient] = None) -> str:
        """Execute cache clearing"""
        client = self.get_client(backend_client)
        device_id = arguments["device_id"]
        application = arguments["application"]
        
        action_data = {
            "type": "clear_cache",
            "application": application
        }
        result = await client.execute_action(device_id, action_data)
        
        # Format action result for AI consumption
        return format_action_result_for_ai("clear_cache", result, application)


class FlushDnsTool(BaseTool):
    """Tool to flush DNS cache"""
    
    @property
    def name(self) -> str:
        return "flush_dns"
    
    @property
    def description(self) -> str:
        return ("Flush the DNS resolver cache on a device. "
                "Use when user reports 'websites not loading' or connectivity problems. "
                "Completely safe operation that clears DNS cache.")
    
    @property
    def input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "device_id": {
                    "type": "string",
                    "description": "The UUID of the device"
                }
            },
            "required": ["device_id"]
        }
    
    async def execute(self, arguments: Dict[str, Any], backend_client: Optional[BackendClient] = None) -> str:
        """Execute DNS cache flush"""
        client = self.get_client(backend_client)
        device_id = arguments["device_id"]
        
        action_data = {
            "type": "flush_dns"
        }
        result = await client.execute_action(device_id, action_data)
        
        # Format action result for AI consumption
        return format_action_result_for_ai("flush_dns", result)


class RestartServiceTool(BaseTool):
    """Tool to restart Windows services"""
    
    @property
    def name(self) -> str:
        return "restart_service"
    
    @property
    def description(self) -> str:
        return ("Restart a Windows service on a device. "
                "Use when a specific service is hung (e.g., Print Spooler, Windows Update). "
                "Blocks critical system services for safety.")
    
    @property
    def input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "device_id": {
                    "type": "string",
                    "description": "The UUID of the device"
                },
                "service_name": {
                    "type": "string",
                    "description": "Name of the Windows service to restart (e.g., 'Spooler', 'wuauserv')"
                }
            },
            "required": ["device_id", "service_name"]
        }
    
    async def execute(self, arguments: Dict[str, Any], backend_client: Optional[BackendClient] = None) -> str:
        """Execute service restart"""
        client = self.get_client(backend_client)
        device_id = arguments["device_id"]
        service_name = arguments["service_name"]
        
        action_data = {
            "type": "restart_service",
            "service_name": service_name
        }
        result = await client.execute_action(device_id, action_data)
        
        # Format action result for AI consumption
        return format_action_result_for_ai("restart_service", result, service_name)