"""
HealthMonitor Agent - Monitors system and agent health
"""

import logging
import psutil
import time
from typing import Dict, Any

from . import BaseAgent
from ..core.config import Config
from ..core.state import StateManager


class HealthMonitorAgent(BaseAgent):
    """Agent responsible for monitoring system and agent health"""

    def __init__(self, config: Config, state_manager: StateManager, agents: Dict[str, BaseAgent]):
        super().__init__('health_monitor', config, state_manager)
        self.agents = agents

    def execute(self) -> Dict[str, Any]:
        """Monitor system and agent health"""
        health_status = {
            'system_health': self.check_system_health(),
            'agent_health': self.check_agent_health(),
            'timestamp': time.time()
        }

        # Determine overall health
        overall_health = 'healthy'
        if health_status['system_health']['status'] != 'healthy':
            overall_health = 'degraded'
        elif not all(agent['status'] == 'healthy' for agent in health_status['agent_health'].values()):
            overall_health = 'warning'

        health_status['overall_health'] = overall_health
        self.state_manager.set_system_health(overall_health)

        self.logger.debug(f"Health check completed: {overall_health}")
        return health_status

    def check_system_health(self) -> Dict[str, Any]:
        """Check system health metrics"""
        try:
            # CPU usage
            cpu_percent = psutil.cpu_percent(interval=1)

            # Memory usage
            memory = psutil.virtual_memory()
            memory_percent = memory.percent

            # Disk usage
            disk = psutil.disk_usage('/')
            disk_percent = disk.percent

            # Determine status
            status = 'healthy'
            issues = []

            if cpu_percent > 90:
                status = 'critical'
                issues.append(f'High CPU usage: {cpu_percent}%')
            elif cpu_percent > 70:
                status = 'warning'
                issues.append(f'Elevated CPU usage: {cpu_percent}%')

            if memory_percent > 90:
                status = 'critical'
                issues.append(f'High memory usage: {memory_percent}%')
            elif memory_percent > 80:
                status = 'warning'
                issues.append(f'Elevated memory usage: {memory_percent}%')

            if disk_percent > 95:
                status = 'critical'
                issues.append(f'Low disk space: {disk_percent}%')
            elif disk_percent > 85:
                status = 'warning'
                issues.append(f'Low disk space: {disk_percent}%')

            return {
                'status': status,
                'cpu_percent': cpu_percent,
                'memory_percent': memory_percent,
                'disk_percent': disk_percent,
                'issues': issues
            }

        except Exception as e:
            self.logger.error(f"System health check failed: {e}")
            return {
                'status': 'error',
                'error': str(e)
            }

    def check_agent_health(self) -> Dict[str, Any]:
        """Check health of all agents"""
        agent_health = {}

        for agent_name, agent in self.agents.items():
            status_info = agent.get_status()
            status = status_info.get('status', 'unknown')

            # Determine health based on status
            if status in ['running', 'success']:
                health = 'healthy'
            elif status in ['error', 'crashed']:
                health = 'unhealthy'
            elif status == 'stopped':
                health = 'stopped'
            else:
                health = 'unknown'

            agent_health[agent_name] = {
                'health': health,
                'status': status,
                'last_update': status_info.get('timestamp'),
                'details': status_info.get('details', {})
            }

        return agent_health