"""
Defined Agent

Generic agent implementation that loads behavior from markdown definitions.
"""
from pathlib import Path
from typing import Optional

from ai_coder.agents.base import Agent, AgentType
from ai_coder.llm.interface import LLMProvider
from ai_coder.tools.base import ToolRegistry

class DefinedAgent(Agent):
    """
    Agent defined by a markdown file.
    
    Parses frontmatter for configuration and body for system prompt.
    """
    
    def __init__(
        self,
        llm: LLMProvider,
        tool_registry: ToolRegistry,
        project_root: Path,
        definition_path: Path,
        agent_type: AgentType,
    ):
        super().__init__(llm, tool_registry, project_root)
        self._definition_path = definition_path
        self._agent_type = agent_type
        self._system_prompt = ""
        self._config = {}
        self._load_definition()

    @property
    def agent_type(self) -> AgentType:
        return self._agent_type

    @property
    def system_prompt(self) -> str:
        return self._system_prompt

    @property
    def allowed_tools(self) -> list[str]:
        # If tools defined in frontmatter, use them. Else default.
        if "tools" in self._config:
            return self._config["tools"]
        return super().allowed_tools

    def _load_definition(self):
        try:
            content = self._definition_path.read_text(encoding="utf-8")
            if content.startswith("---"):
                parts = content.split("---", 2)
                if len(parts) >= 3:
                    # Parse frontmatter (simple key: value)
                    import yaml
                    try:
                        self._config = yaml.safe_load(parts[1])
                    except:
                        pass
                    
                    self._system_prompt = parts[2].strip()
            else:
                self._system_prompt = content
        except Exception as e:
            self._system_prompt = f"Error loading definition: {e}"
