"""
Coordinator Agent - Orchestrates workflow between agents
"""

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

from . import BaseAgent
from ..core.config import Config
from ..core.state import StateManager
from .file_watcher import FileWatcherAgent
from .vital_extractor import VitalExtractorAgent
from .context_updater import ContextUpdaterAgent
from .health_monitor import HealthMonitorAgent


class CoordinatorAgent(BaseAgent):
    """Agent responsible for coordinating workflow between all other agents"""

    def __init__(self, config: Config, state_manager: StateManager):
        super().__init__('coordinator', config, state_manager)
        self.agents = {}
        self._initialize_agents()

    def _initialize_agents(self):
        """Initialize all subordinate agents"""
        # Create agents
        self.agents['file_watcher'] = FileWatcherAgent(self.config, self.state_manager)
        self.agents['vital_extractor'] = VitalExtractorAgent(self.config, self.state_manager)
        self.agents['context_updater'] = ContextUpdaterAgent(self.config, self.state_manager)
        self.agents['health_monitor'] = HealthMonitorAgent(self.config, self.state_manager, self.agents)

        # Connect agents (vital_extractor listens to file_watcher, etc.)
        self._setup_agent_connections()

    def _setup_agent_connections(self):
        """Setup event connections between agents"""
        # FileWatcher events go to VitalExtractor
        # VitalExtractor events go to ContextUpdater
        # This is handled through the event system in EventDrivenAgent

        # Note: In this implementation, agents communicate through events
        # The coordinator doesn't directly route events, but ensures agents are running
        pass

    def execute(self) -> Dict[str, Any]:
        """Coordinate agent execution and monitor workflow"""
        results = {}

        # Execute FileWatcher first
        if self.config.is_agent_enabled('file_watcher'):
            try:
                fw_result = self.agents['file_watcher'].execute()
                results['file_watcher'] = fw_result

                # If files changed, trigger VitalExtractor
                if fw_result.get('files_changed', 0) > 0:
                    changed_files = fw_result.get('changed_files_list', [])
                    event = {
                        'type': 'files_changed',
                        'changed_files': changed_files,
                        'timestamp': time.time()
                    }

                    if self.config.is_agent_enabled('vital_extractor'):
                        ve_result = self.agents['vital_extractor'].process_event(event)
                        results['vital_extractor'] = ve_result

                        # If vital info extracted, trigger ContextUpdater
                        if ve_result.get('vital_info_extracted', 0) > 0:
                            vital_event = {
                                'type': 'vital_info_extracted',
                                'vital_info': ve_result.get('vital_info', {}),
                                'timestamp': time.time()
                            }

                            if self.config.is_agent_enabled('context_updater'):
                                cu_result = self.agents['context_updater'].process_event(vital_event)
                                results['context_updater'] = cu_result

            except Exception as e:
                self.logger.error(f"FileWatcher execution failed: {e}")
                results['file_watcher'] = {'error': str(e)}

        # Execute HealthMonitor
        if self.config.is_agent_enabled('health_monitor'):
            try:
                hm_result = self.agents['health_monitor'].execute()
                results['health_monitor'] = hm_result
            except Exception as e:
                self.logger.error(f"HealthMonitor execution failed: {e}")
                results['health_monitor'] = {'error': str(e)}

        # Update last scan timestamp
        self.state_manager.set_last_scan()

        return {
            'coordination_cycle': 'completed',
            'agents_executed': len(results),
            'results': results
        }

    def start_all_agents(self):
        """Start all subordinate agents"""
        for agent_name, agent in self.agents.items():
            if self.config.is_agent_enabled(agent_name):
                try:
                    agent.start()
                    self.logger.info(f"Started agent: {agent_name}")
                except Exception as e:
                    self.logger.error(f"Failed to start agent {agent_name}: {e}")

    def stop_all_agents(self):
        """Stop all subordinate agents"""
        for agent_name, agent in self.agents.items():
            try:
                agent.stop()
                self.logger.info(f"Stopped agent: {agent_name}")
            except Exception as e:
                self.logger.error(f"Failed to stop agent {agent_name}: {e}")

    def get_agent_status(self) -> Dict[str, Any]:
        """Get status of all agents"""
        status = {}
        for agent_name, agent in self.agents.items():
            status[agent_name] = {
                'running': agent.is_running,
                'status': agent.get_status()
            }
        return status

    def override_agent_config(self, agent_name: str, enabled: bool):
        """Override agent configuration at runtime"""
        self.config.set(f'agents.{agent_name}.enabled', enabled)
        if enabled and not self.agents[agent_name].is_running:
            self.agents[agent_name].start()
        elif not enabled and self.agents[agent_name].is_running:
            self.agents[agent_name].stop()