from typing import Dict, Optional, List
from pydantic import BaseModel, Field
from enum import Enum
from pathlib import Path

from .logger import log_event


class AgentMode(str, Enum):
    """Agent mode types"""

    PRIMARY = "primary"  # Main agent mode
    SUBAGENT = "subagent"  # Sub-agent for specific tasks
    ALL = "all"  # Can be used in any mode


class AgentConfig(BaseModel):
    """Agent configuration"""

    name: str = Field(..., description="Agent name")
    description: Optional[str] = Field(None, description="Agent description")
    mode: AgentMode = Field(AgentMode.PRIMARY, description="Agent mode")
    prompt: Optional[str] = Field(None, description="Additional system prompt")
    temperature: float = Field(0.7, description="Temperature for LLM")
    max_steps: Optional[int] = Field(None, description="Maximum steps for agent")
    readonly: bool = Field(False, description="Whether agent is in readonly mode")


class AgentManager:
    """Manage different agent types and switching"""

    def __init__(self):
        self.agents: Dict[str, AgentConfig] = {}
        self.current_agent: Optional[str] = None
        self._register_builtin_agents()

    def _register_builtin_agents(self):
        """Register built-in agents"""
        # Plan agent - planning and analysis agent
        self.register_agent(
            AgentConfig(
                name="plan",
                description="Planning agent for task analysis (readonly mode)",
                mode=AgentMode.PRIMARY,
                readonly=True,
                prompt=self._get_plan_prompt(),
            )
        )

        # Build agent - specialized coding agent with enhanced capabilities
        self.register_agent(
            AgentConfig(
                name="build",
                description="Specialized coding agent with comprehensive development workflow support",
                mode=AgentMode.PRIMARY,
                readonly=False,
                prompt=self._get_build_prompt(),
            )
        )

        # Web agent - browser automation agent
        self.register_agent(
            AgentConfig(
                name="web",
                description="Web automation agent for browser tasks",
                mode=AgentMode.ALL,
                readonly=False,
                prompt=self._get_web_prompt(),
            )
        )

    def _get_plan_prompt(self) -> str:
        """Get plan mode system prompt from file"""
        try:
            # Try to load from src/assets/prompts/agents/plan.txt
            prompt_path = Path(__file__).parent.parent / "assets" / "prompts" / "agents" / "plan.txt"
            if prompt_path.exists():
                return prompt_path.read_text(encoding="utf-8")
            else:
                # Fallback to basic prompt if file not found
                log_event("plan_prompt_file_not_found", path=str(prompt_path))
                return "You are a planning agent focused on task analysis (readonly mode)."
        except Exception as e:
            log_event("plan_prompt_load_error", error=str(e))
            return "You are a planning agent focused on task analysis (readonly mode)."

    def _get_build_prompt(self) -> str:
        """Get build agent system prompt from file"""
        try:
            # Try to load from src/assets/prompts/agents/build.txt
            prompt_path = Path(__file__).parent.parent / "assets" / "prompts" / "agents" / "build.txt"
            if prompt_path.exists():
                return prompt_path.read_text(encoding="utf-8")
            else:
                # Fallback to basic prompt if file not found
                return "You are a professional coding agent focused on software development tasks."
        except Exception as e:
            log_event("build_prompt_load_error", error=str(e))
            return "You are a professional coding agent focused on software development tasks."

    def _get_web_prompt(self) -> str:
        """Get web agent system prompt from file"""
        try:
            # Try to load from src/assets/prompts/agents/web.txt
            prompt_path = Path(__file__).parent.parent / "assets" / "prompts" / "agents" / "web.txt"
            if prompt_path.exists():
                return prompt_path.read_text(encoding="utf-8")
            else:
                # Fallback to basic prompt if file not found
                log_event("web_prompt_file_not_found", path=str(prompt_path))
                return "You are a web automation agent that uses browser-use to complete tasks."
        except Exception as e:
            log_event("web_prompt_load_error", error=str(e))
            return "You are a web automation agent that uses browser-use to complete tasks."

    def register_agent(self, config: AgentConfig):
        """Register an agent"""
        self.agents[config.name] = config

    def get_agent(self, name: str) -> Optional[AgentConfig]:
        """Get agent configuration by name"""
        return self.agents.get(name)

    def switch_agent(self, name: str) -> Optional[AgentConfig]:
        """Switch to a different agent"""
        agent = self.get_agent(name)
        if agent:
            self.current_agent = name
        return agent

    def get_current_agent(self) -> Optional[AgentConfig]:
        """Get current agent configuration"""
        if self.current_agent:
            return self.agents.get(self.current_agent)
        return None

    def get_switch_message(self, from_agent: str, to_agent: str) -> str:
        """Get message for agent switching"""
        if from_agent == "plan" and to_agent == "build":
            return """<system-reminder>
Your operational mode has changed from plan to build.
You are no longer in read-only mode.
You are permitted to make file changes, run shell commands, and utilize your tools as needed.
</system-reminder>"""
        return f"<system-reminder>Switched from {from_agent} to {to_agent} mode.</system-reminder>"
