"""
Read-only tools for device telemetry and process information
"""

from typing import Any, Dict, Optional

from app.tools.base import BaseTool
from app.client.backend_client import BackendClient
from app.formatters.telemetry_formatter import format_telemetry_for_ai, format_processes_for_ai


class GetDeviceTelemetryTool(BaseTool):
    """Tool to get device system metrics (CPU, memory, disk)"""
    
    @property
    def name(self) -> str:
        return "get_device_telemetry"
    
    @property
    def description(self) -> str:
        return ("Get current CPU, memory, disk usage and process count for a device. "
                "Use this first when user mentions slowness, high resource usage, or performance issues. "
                "Returns real-time system metrics.")
    
    @property
    def input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "device_id": {
                    "type": "string",
                    "description": "The UUID of the device to get telemetry for"
                }
            },
            "required": ["device_id"]
        }
    
    async def execute(self, arguments: Dict[str, Any], backend_client: Optional[BackendClient] = None) -> str:
        """Execute telemetry retrieval"""
        client = self.get_client(backend_client)
        device_id = arguments["device_id"]
        telemetry = await client.get_device_telemetry(device_id)
        
        # Format telemetry data for AI consumption
        return format_telemetry_for_ai(telemetry)


class GetDeviceProcessesTool(BaseTool):
    """Tool to get running processes on a device"""
    
    @property
    def name(self) -> str:
        return "get_device_processes"
    
    @property
    def description(self) -> str:
        return ("Get list of running processes with CPU and memory usage for a device. "
                "Use this to identify which applications are consuming resources (e.g., Chrome, Outlook). "
                "Returns process name, PID, CPU%, and memory usage.")
    
    @property
    def input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "device_id": {
                    "type": "string",
                    "description": "The UUID of the device to get processes for"
                }
            },
            "required": ["device_id"]
        }
    
    async def execute(self, arguments: Dict[str, Any], backend_client: Optional[BackendClient] = None) -> str:
        """Execute process list retrieval"""
        client = self.get_client(backend_client)
        device_id = arguments["device_id"]
        processes = await client.get_device_processes(device_id)
        
        # Format process list for AI consumption
        return format_processes_for_ai(processes)


class ListDevicesTool(BaseTool):
    """Tool to list all devices from the backend (no agent connection required)."""

    @property
    def name(self) -> str:
        return "list_devices"

    @property
    def description(self) -> str:
        return ("List all devices from the backend. Does not require devices to have an agent connected. "
                "Use this to see the full device inventory, online/offline status, and basic info. "
                "Optionally filter by organization_id.")

    @property
    def input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "organization_id": {
                    "type": "string",
                    "description": "Optional. Filter devices by organization ID."
                }
            },
            "required": []
        }

    async def execute(self, arguments: Dict[str, Any], backend_client: Optional[BackendClient] = None) -> str:
        """Fetch all devices from backend (backend API only, no agent connection)."""
        client = self.get_client(backend_client)
        organization_id = arguments.get("organization_id")
        devices = await client.get_devices(organization_id=organization_id)

        if not devices:
            return "No devices found in the backend." + (
                f" (organization_id={organization_id})" if organization_id else ""
            )

        lines = [f"Total devices: {len(devices)}"]
        for i, d in enumerate(devices, 1):
            device_id = d.get("device_id") or d.get("id") or "N/A"
            name = d.get("name") or d.get("hostname") or "Unknown"
            status = d.get("status") or "unknown"
            hostname = d.get("hostname", "")
            os_info = d.get("os_name") or ""
            if d.get("os_version"):
                os_info = f"{os_info} {d.get('os_version')}".strip()
            last_seen = d.get("last_seen", "")
            lines.append(
                f"{i}. {name} | id: {device_id} | status: {status} | hostname: {hostname} | os: {os_info} | last_seen: {last_seen}"
            )
        return "\n".join(lines)