"""
Custom Agent Support

Allows users to create custom agents from configuration files.
"""

import time
from pathlib import Path
from typing import Any, Optional

from groknroll.agents.base_agent import AgentCapability, AgentConfig, AgentResponse, BaseAgent
from groknroll.config.agent_config import AgentConfigData
from groknroll.core.rlm_integration import RLMConfig, RLMIntegration


class CustomAgent(BaseAgent):
    """
    Custom Agent

    Created from user configuration (groknroll.json or .groknroll/agent/<name>.md).
    Supports custom capabilities, system prompts, and permissions.
    """

    def __init__(
        self, config_data: AgentConfigData, project_path: Path, system_prompt: Optional[str] = None
    ):
        """
        Initialize custom agent from configuration

        Args:
            config_data: Agent configuration data
            project_path: Project root path
            system_prompt: Optional system prompt override
        """
        # Map capability strings to enum values
        capability_map = {
            "read_files": AgentCapability.READ_FILES,
            "write_files": AgentCapability.WRITE_FILES,
            "edit_files": AgentCapability.EDIT_FILES,
            "delete_files": AgentCapability.DELETE_FILES,
            "execute_bash": AgentCapability.EXECUTE_BASH,
            "git_operations": AgentCapability.GIT_OPERATIONS,
            "analyze_code": AgentCapability.ANALYZE_CODE,
            "search_code": AgentCapability.SEARCH_CODE,
        }

        capabilities = [
            capability_map[cap] for cap in config_data.capabilities if cap in capability_map
        ]

        config = AgentConfig(
            name=config_data.name,
            description=config_data.description,
            capabilities=capabilities,
            model=config_data.model,
            max_cost=config_data.max_cost,
            timeout=config_data.timeout,
        )

        super().__init__(config, project_path)

        # Store custom configuration
        self.temperature = config_data.temperature
        self.max_steps = config_data.max_steps
        self.permissions = config_data.permissions or {}
        self.system_prompt = system_prompt or config_data.system_prompt

        # Initialize RLM
        rlm_config = RLMConfig(
            model=config_data.model,
            max_cost=config_data.max_cost,
            timeout_seconds=config_data.timeout,
        )
        self.rlm = RLMIntegration(rlm_config)

    def execute(self, task: str, context: Optional[dict[str, Any]] = None) -> AgentResponse:
        """
        Execute task with custom agent

        Args:
            task: Task description
            context: Additional context

        Returns:
            AgentResponse
        """
        start_time = time.time()

        try:
            # Prepare context
            exec_context = {
                "agent": self.config.name,
                "agent_type": "custom",
                "capabilities": self.get_capabilities(),
                "project_path": str(self.project_path),
                "permissions": self.permissions,
                **(context or {}),
            }

            # Build enhanced task with system prompt
            task_parts = [f"Task: {task}"]

            if self.system_prompt:
                task_parts.insert(0, f"System: {self.system_prompt}")

            task_parts.append(
                f"""
You are a CUSTOM AGENT named "{self.config.name}".

Description: {self.config.description}

Capabilities: {", ".join(self.get_capabilities())}

Execute the task within your capabilities.
"""
            )

            enhanced_task = "\n\n".join(task_parts)

            # Execute with RLM
            result = self.rlm.complete(task=enhanced_task, context=exec_context)

            elapsed_time = time.time() - start_time

            response = AgentResponse(
                success=result.success,
                message=result.response if result.success else result.error or "Unknown error",
                agent_name=self.config.name,
                task=task,
                cost=result.total_cost,
                time=elapsed_time,
                metadata={
                    "iterations": result.iterations,
                    "rlm_success": result.success,
                    "agent_type": "custom",
                    "temperature": self.temperature,
                    "max_steps": self.max_steps,
                },
            )

            self._log_execution(response)
            return response

        except Exception as e:
            elapsed_time = time.time() - start_time

            response = AgentResponse(
                success=False,
                message=f"Custom agent error: {e}",
                agent_name=self.config.name,
                task=task,
                time=elapsed_time,
            )

            self._log_execution(response)
            return response


def create_agent_from_config(config_data: AgentConfigData, project_path: Path) -> CustomAgent:
    """
    Create custom agent from configuration

    Args:
        config_data: Agent configuration data
        project_path: Project root path

    Returns:
        CustomAgent instance
    """
    return CustomAgent(config_data, project_path)
