"""
Plan Agent

Read-only agent for planning and analysis without making changes.
This agent can read files and analyze code but cannot modify anything.
"""

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

from groknroll.agents.base_agent import AgentCapability, AgentConfig, AgentResponse, BaseAgent
from groknroll.core.rlm_integration import RLMConfig, RLMIntegration
from groknroll.operations.file_ops import FileOperations
from groknroll.prompts.system import build_system_prompt, PROMPT_PLAN


class PlanAgent(BaseAgent):
    """
    Plan Agent - Read-Only

    Capabilities:
    - Read files
    - Analyze code
    - Search code

    Use for:
    - Planning implementations
    - Code reviews
    - Architecture analysis
    - Understanding codebases
    - Generating documentation

    CANNOT:
    - Write/edit/delete files
    - Execute bash commands
    - Make git commits
    """

    def __init__(
        self,
        project_path: Path,
        model: str = "gpt-4o-mini",
        max_cost: float = 5.0,
        timeout: int = 300,
    ):
        """
        Initialize plan agent

        Args:
            project_path: Project root path
            model: LLM model to use
            max_cost: Maximum cost per execution
            timeout: Timeout in seconds
        """
        # Plan agent has read-only capabilities
        config = AgentConfig(
            name="plan",
            description="Read-only agent for planning and analysis",
            capabilities=[
                AgentCapability.READ_FILES,
                AgentCapability.ANALYZE_CODE,
                AgentCapability.SEARCH_CODE,
            ],
            model=model,
            max_cost=max_cost,
            timeout=timeout,
        )

        super().__init__(config, project_path)

        # Initialize read-only file operations
        self.file_ops = FileOperations(project_path, create_backups=False)

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

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

        Args:
            task: Task description
            context: Additional context

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

        try:
            # Prepare context with available operations
            exec_context = {
                "agent": "plan",
                "capabilities": self.get_capabilities(),
                "project_path": str(self.project_path),
                "operations": {
                    "file": "Read-only: can read files, cannot write/edit/delete",
                    "bash": "Not available (read-only agent)",
                    "git": "Not available (read-only agent)",
                },
                "mode": "READ-ONLY",
                **(context or {}),
            }

            # Build comprehensive system prompt for plan agent
            system_prompts = build_system_prompt(
                provider_id="anthropic",
                model_id=self.config.model,
                agent_name="plan",
                project_path=self.project_path,
                include_environment=True,
            )
            system_prompt = "\n\n".join(system_prompts)

            # Add plan-specific context
            plan_context = f"""
# Plan Agent - READ-ONLY Mode

You are operating in READ-ONLY mode. You can:
- Read and analyze files
- Search the codebase
- Understand architecture
- Create detailed implementation plans

You CANNOT:
- Modify, write, or delete any files
- Execute bash commands
- Make git commits or changes

## Available Operations (read_ops)
- `read_file(path)` - Read file contents
- `list_files(pattern)` - Find files by pattern

## Your Goals
1. Thoroughly understand the request
2. Explore relevant parts of the codebase
3. Consider multiple approaches and their tradeoffs
4. Create a clear, actionable implementation plan
5. Identify potential risks or edge cases

# Task
{task}
"""

            enhanced_task = f"{system_prompt}\n\n{plan_context}"

            # 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,
                    "mode": "read-only",
                },
            )

            self._log_execution(response)
            return response

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

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

            self._log_execution(response)
            return response

    # =========================================================================
    # Convenience Methods (Read-Only Operations)
    # =========================================================================

    def read_file(self, path: Path) -> str:
        """Read file (convenience method)"""
        self.require(AgentCapability.READ_FILES)
        result = self.file_ops.read_file(path)
        if not result.success:
            raise RuntimeError(result.message)
        return result.message

    def list_files(self, pattern: str = "*.py", recursive: bool = True) -> list[str]:
        """List files matching pattern (convenience method)"""
        self.require(AgentCapability.READ_FILES)
        result = self.file_ops.list_files(pattern=pattern, recursive=recursive)
        if not result.success:
            raise RuntimeError(result.message)
        return result.message.split("\n") if result.message else []

    def analyze(self, task: str) -> str:
        """Analyze and plan (convenience method)"""
        response = self.execute(task)
        if not response.success:
            raise RuntimeError(response.message)
        return response.message
