"""
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


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 {}),
            }

            # Add instructions for planning mode
            enhanced_task = f"""Task: {task}

You are the PLAN agent with READ-ONLY access:
- Can read files
- Can analyze code
- Can search code
- CANNOT modify files
- CANNOT execute bash
- CANNOT use git

Your goal is to:
1. Understand the codebase
2. Analyze architecture
3. Plan implementations
4. Provide recommendations
5. Generate documentation

Available in context:
- file_ops: FileOperations instance (read-only)

Example usage in RLM code:
```python
# Read file
result = file_ops.read_file(Path("example.py"))
if result.success:
    content = result.message
    # Analyze content...

# List files
result = file_ops.list_files(pattern="*.py", recursive=True)
if result.success:
    files = result.message.split("\\n")
    # Process files...
```

Analyze and plan for the task. DO NOT attempt to modify files.
"""

            # 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
