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

from pygeai_orchestration.core.base.orchestrator import BaseOrchestrator, OrchestratorConfig
from pygeai_orchestration.core.base.pattern import PatternResult

logger = logging.getLogger("pygeai_orchestration")


class GEAIOrchestrator(BaseOrchestrator):
    def __init__(self, config: OrchestratorConfig):
        super().__init__(config)
        self._execution_history: List[Dict[str, Any]] = []

    async def orchestrate(
        self, task: str, pattern: str, context: Optional[Dict[str, Any]] = None
    ) -> PatternResult:
        logger.info(f"Orchestrating task with pattern '{pattern}': {task[:50]}...")

        pattern_instance = self.get_pattern(pattern)
        if pattern_instance is None:
            error_msg = f"Pattern '{pattern}' not found. Available: {self.list_patterns()}"
            logger.error(error_msg)
            return PatternResult(success=False, result=None, iterations=0, error=error_msg)

        try:
            result = await pattern_instance.execute(task, context)

            self._execution_history.append(
                {
                    "task": task,
                    "pattern": pattern,
                    "success": result.success,
                    "iterations": result.iterations,
                    "result": result.result,
                }
            )

            logger.info(
                f"Orchestration {'succeeded' if result.success else 'failed'} "
                f"after {result.iterations} iterations"
            )

            return result

        except Exception as e:
            logger.error(f"Orchestration error: {str(e)}")
            return PatternResult(success=False, result=None, iterations=0, error=str(e))

    async def coordinate_agents(self, agents: List[str], task: str) -> Dict[str, Any]:
        logger.info(f"Coordinating {len(agents)} agents for task: {task[:50]}...")
        return {"status": "not_implemented", "agents": agents, "task": task}

    def get_execution_history(self) -> List[Dict[str, Any]]:
        return self._execution_history.copy()
