"""
Build Agent

Full-access agent that can read, write, execute bash, and use git.
This is the primary agent for implementing features and making changes.
"""

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.bash_ops import BashOperations
from groknroll.operations.file_ops import FileOperations
from groknroll.operations.git_ops import GitOperations
from groknroll.prompts.system import build_system_prompt, PROMPT_AGENTIC


class BuildAgent(BaseAgent):
    """
    Build Agent - Full Access

    Capabilities:
    - Read/write/edit/delete files
    - Execute bash commands
    - Git operations
    - Code analysis
    - Code search

    Use for:
    - Implementing new features
    - Fixing bugs
    - Refactoring code
    - Running tests
    - Building projects
    """

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

        Args:
            project_path: Project root path
            model: LLM model to use
            max_cost: Maximum cost per execution
            timeout: Timeout in seconds
        """
        # Build agent has all capabilities
        config = AgentConfig(
            name="build",
            description="Full-access agent for building and modifying code",
            capabilities=[
                AgentCapability.READ_FILES,
                AgentCapability.WRITE_FILES,
                AgentCapability.EDIT_FILES,
                AgentCapability.DELETE_FILES,
                AgentCapability.EXECUTE_BASH,
                AgentCapability.GIT_OPERATIONS,
                AgentCapability.ANALYZE_CODE,
                AgentCapability.SEARCH_CODE,
            ],
            model=model,
            max_cost=max_cost,
            timeout=timeout,
        )

        super().__init__(config, project_path)

        # Initialize operations
        self.file_ops = FileOperations(project_path)
        self.bash_ops = BashOperations(project_path)

        # Initialize git ops (may fail if not a git repo)
        try:
            self.git_ops = GitOperations(project_path)
        except RuntimeError:
            self.git_ops = None

        # 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 build task

        Args:
            task: Task description
            context: Additional context

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

        try:
            # Prepare context with available operations
            exec_context = {
                "agent": "build",
                "capabilities": self.get_capabilities(),
                "project_path": str(self.project_path),
                "operations": {
                    "file": "Available: read, write, edit, delete",
                    "bash": "Available: execute commands",
                    "git": "Available: status, add, commit, push, etc."
                    if self.git_ops
                    else "Not available",
                },
                **(context or {}),
            }

            # Build comprehensive system prompt
            system_prompts = build_system_prompt(
                provider_id="anthropic",  # Default, will be auto-detected in streaming
                model_id=self.config.model,
                agent_name="build",
                project_path=self.project_path,
                include_environment=True,
            )
            system_prompt = "\n\n".join(system_prompts)

            # Add agent-specific capabilities context
            capabilities_context = f"""
# Available Operations

You have access to the following operations through RLM:

## File Operations (file_ops)
- `read_file(path)` - Read file contents
- `write_file(path, content)` - Write/create file
- `edit_file(path, old, new)` - Edit file with replacement
- `list_files(pattern)` - List files matching pattern

## Bash Operations (bash_ops)
- `execute(command)` - Run shell command

## Git Operations (git_ops)
- `status()` - Get git status
- `add(files)` - Stage files
- `commit(message)` - Create commit
- `push()` - Push to remote
{"(Git operations available)" if self.git_ops else "(Git not available - not a git repo)"}

# Task
{task}
"""

            enhanced_task = f"{system_prompt}\n\n{capabilities_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},
            )

            self._log_execution(response)
            return response

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

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

            self._log_execution(response)
            return response

    # =========================================================================
    # Convenience Methods (Direct 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 write_file(self, path: Path, content: str) -> None:
        """Write file (convenience method)"""
        self.require(AgentCapability.WRITE_FILES)
        result = self.file_ops.write_file(path, content, overwrite=True)
        if not result.success:
            raise RuntimeError(result.message)

    def run_command(self, command: str) -> str:
        """Run bash command (convenience method)"""
        self.require(AgentCapability.EXECUTE_BASH)
        result = self.bash_ops.execute(command)
        if not result.success:
            raise RuntimeError(result.stderr)
        return result.stdout

    def git_status(self) -> str:
        """Get git status (convenience method)"""
        self.require(AgentCapability.GIT_OPERATIONS)
        if not self.git_ops:
            raise RuntimeError("Git not available")

        status = self.git_ops.status()
        return f"Branch: {status.branch}, Staged: {len(status.staged)}, Unstaged: {len(status.unstaged)}"
