"""
Response handler for processing and executing AI responses
"""
from typing import Dict, List, Optional, Any, Union
from .interface import Response, ResponseType, CodeAction, CommandAction
from ..workspace.manager import WorkspaceManager
from ..terminal.terminal_manager import TerminalManager
import asyncio
import json

class ResponseHandler:
    def __init__(self, 
                workspace: WorkspaceManager,
                terminal: TerminalManager):
        self.workspace = workspace
        self.terminal = terminal
        
    async def process_response(self, response: Response) -> Dict[str, Any]:
        """Process and execute the AI response"""
        result = {
            "success": False,
            "type": response.type.value,
            "details": None,
            "error": None
        }
        
        try:
            if response.type == ResponseType.CODE:
                result.update(await self._handle_code_action(response.content))
            elif response.type == ResponseType.COMMAND:
                result.update(await self._handle_command_action(response.content))
            elif response.type == ResponseType.ERROR:
                result.update({
                    "error": response.content,
                    "success": False
                })
            else:
                result.update({
                    "success": True,
                    "details": response.content
                })
                
        except Exception as e:
            result.update({
                "success": False,
                "error": str(e)
            })
            
        return result
        
    async def _handle_code_action(self, action: CodeAction) -> Dict[str, Any]:
        """Handle code modification actions"""
        result = {
            "action": action.action_type,
            "file": action.file_path,
            "success": False
        }
        
        try:
            if action.action_type == 'create':
                # Create new file
                await self.workspace.write_file(
                    action.file_path,
                    action.content
                )
                result["success"] = True
                
            elif action.action_type == 'modify':
                # Modify existing file
                # First create backup
                backup_path = await self.workspace.create_backup(action.file_path)
                
                # Read current content if needed for partial modification
                if action.line_number:
                    current_content = await self.workspace.read_file(action.file_path)
                    lines = current_content.splitlines()
                    lines[action.line_number - 1] = action.content
                    new_content = '\n'.join(lines)
                else:
                    new_content = action.content
                    
                # Write new content
                await self.workspace.write_file(
                    action.file_path,
                    new_content
                )
                result.update({
                    "success": True,
                    "backup": backup_path
                })
                
            elif action.action_type == 'delete':
                # Delete file with backup
                backup_path = await self.workspace.create_backup(action.file_path)
                await self.workspace.delete_file(action.file_path)
                result.update({
                    "success": True,
                    "backup": backup_path
                })
                
            elif action.action_type == 'rename':
                # Rename file
                await self.workspace.rename_file(
                    action.file_path,
                    action.content  # new path
                )
                result["success"] = True
                
        except Exception as e:
            result["error"] = str(e)
            
        return result
        
    async def _handle_command_action(self, action: CommandAction) -> Dict[str, Any]:
        """Handle terminal command actions"""
        result = {
            "command": action.command,
            "success": False
        }
        
        try:
            # Change directory if specified
            if action.cwd:
                self.terminal.cd(action.cwd)
                
            # Execute command
            cmd_result = await self.terminal.execute_command(
                command=action.command,
                timeout=action.timeout
            )
            
            result.update({
                "success": cmd_result.status.value == "success",
                "output": cmd_result.output,
                "error": cmd_result.error,
                "duration": cmd_result.duration,
                "exit_code": cmd_result.exit_code
            })
            
            # Verify expected output if specified
            if action.expected_output and cmd_result.status.value == "success":
                for expected in action.expected_output:
                    if expected not in cmd_result.output:
                        result.update({
                            "success": False,
                            "error": f"Expected output not found: {expected}"
                        })
                        break
                        
        except Exception as e:
            result["error"] = str(e)
            
        return result
        
    async def validate_response(self, response: Response) -> bool:
        """Validate response before execution"""
        try:
            if response.type == ResponseType.CODE:
                action = response.content
                if action.action_type in ['modify', 'delete']:
                    # Check if file exists
                    file_info = self.workspace.get_file_info(action.file_path)
                    return True
                elif action.action_type == 'create':
                    # Check if path is valid and file doesn't exist
                    path = self.workspace.workspace_path / action.file_path
                    return not path.exists()
                    
            elif response.type == ResponseType.COMMAND:
                action = response.content
                # Basic command validation - could be enhanced
                return bool(action.command.strip())
                
            return True
            
        except Exception:
            return False
            
    async def rollback_action(self, action_result: Dict[str, Any]) -> bool:
        """Rollback a failed action"""
        try:
            if not action_result["success"] and action_result.get("backup"):
                # Restore from backup
                await self.workspace.restore_latest_backup(
                    action_result["file"]
                )
                return True
                
            return False
            
        except Exception:
            return False
            
    def format_result(self, result: Dict[str, Any]) -> str:
        """Format action result for display"""
        if result["success"]:
            output = "✓ Action completed successfully\n"
            if result.get("details"):
                output += f"Details: {result['details']}\n"
            if result.get("output"):
                output += f"Output: {result['output']}\n"
        else:
            output = "✗ Action failed\n"
            if result.get("error"):
                output += f"Error: {result['error']}\n"
                
        return output
