"""Git operations tool"""

import subprocess
from typing import Dict, Any


class GitTool:
    """Git operations tool"""
    
    def __init__(self, config: Dict[str, Any]):
        """Initialize git tool
        
        Args:
            config: Tool configuration
        """
        self.config = config
        self.description = "Git operations tool"
    
    def execute(self, operation: str, **params) -> str:
        """Execute git operation
        
        Args:
            operation: Git operation to perform
            params: Operation parameters
            
        Returns:
            Operation result
        """
        operations = {
            'status': self.status,
            'add': self.add,
            'commit': self.commit,
            'push': self.push,
            'pull': self.pull,
            'branch': self.branch,
            'log': self.log
        }
        
        if operation in operations:
            return operations[operation](**params)
        else:
            return f"Unknown git operation: {operation}"
    
    def status(self) -> str:
        """Get git status
        
        Returns:
            Git status output
        """
        return self._run_git_command("status")
    
    def add(self, files: str = ".") -> str:
        """Add files to git
        
        Args:
            files: Files to add
            
        Returns:
            Command output
        """
        return self._run_git_command(f"add {files}")
    
    def commit(self, message: str) -> str:
        """Commit changes
        
        Args:
            message: Commit message
            
        Returns:
            Command output
        """
        return self._run_git_command(f"commit -m '{message}'")
    
    def push(self, remote: str = "origin", branch: str = "main") -> str:
        """Push changes
        
        Args:
            remote: Remote repository
            branch: Branch name
            
        Returns:
            Command output
        """
        return self._run_git_command(f"push {remote} {branch}")
    
    def pull(self, remote: str = "origin", branch: str = "main") -> str:
        """Pull changes
        
        Args:
            remote: Remote repository
            branch: Branch name
            
        Returns:
            Command output
        """
        return self._run_git_command(f"pull {remote} {branch}")
    
    def branch(self) -> str:
        """List branches
        
        Returns:
            Command output
        """
        return self._run_git_command("branch")
    
    def log(self, limit: int = 5) -> str:
        """Show commit log
        
        Args:
            limit: Number of commits to show
            
        Returns:
            Command output
        """
        return self._run_git_command(f"log -n {limit}")
    
    def _run_git_command(self, command: str) -> str:
        """Run git command
        
        Args:
            command: Git command to run
            
        Returns:
            Command output
        """
        try:
            result = subprocess.run(
                f"git {command}",
                shell=True,
                capture_output=True,
                text=True,
                timeout=60  # 60 second timeout
            )
            
            output = ""
            if result.stdout:
                output += result.stdout
            if result.stderr:
                output += f"\nError: {result.stderr}"
            
            return output.strip() or f"Command executed with exit code: {result.returncode}"
        except Exception as e:
            return f"Error executing git command: {str(e)}"
    
    def get_schema(self) -> Dict[str, Any]:
        """Get tool schema
        
        Returns:
            JSON Schema for the tool
        """
        return {
            "name": "git",
            "description": self.description,
            "parameters": {
                "type": "object",
                "properties": {
                    "operation": {
                        "type": "string",
                        "enum": ["status", "add", "commit", "push", "pull", "branch", "log"],
                        "description": "Git operation to perform"
                    },
                    "files": {
                        "type": "string",
                        "description": "Files to add for add operation"
                    },
                    "message": {
                        "type": "string",
                        "description": "Commit message for commit operation"
                    },
                    "remote": {
                        "type": "string",
                        "description": "Remote repository for push/pull operations"
                    },
                    "branch": {
                        "type": "string",
                        "description": "Branch name for push/pull operations"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Number of commits to show for log operation"
                    }
                },
                "required": ["operation"]
            }
        }
