"""
Interactive chat commands for the MiniMax Code CLI.

Provides an interactive REPL-style interface for conversational coding assistance.
"""

import os
import json
from typing import Any, List, Dict

from .base import BaseCommand


class ChatCommands(BaseCommand):
    """Commands for interactive coding assistance."""
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.context_files = []
        self.conversation_history = []
    
    def start(self, args: Any) -> bool:
        """Start an interactive coding session."""
        self.show_notification("🤖 Starting MiniMax Code interactive session", level='info')
        self.show_notification("Type 'help' for commands, 'exit' to quit", level='info')
        
        # Load initial context
        if args.context:
            if os.path.isfile(args.context):
                self._add_file_to_context(args.context)
            else:
                self.show_notification(f"Context file not found: {args.context}", level='warning')
        
        if args.project:
            self._load_project_context(args.project)
        
        self.presenter.show_separator()
        
        # Main chat loop
        while True:
            try:
                user_input = input("\n💬 You: ").strip()
                
                if not user_input:
                    continue
                
                # Handle special commands
                cmd = user_input.lower()
                if cmd in ['exit', 'quit', 'bye']:
                    self.show_notification("Goodbye! 👋", level='info')
                    break
                elif cmd == 'help':
                    self._show_help()
                    continue
                elif cmd == 'context':
                    self._show_context()
                    continue
                elif user_input.startswith('add '):
                    file_path = user_input[4:].strip()
                    self._add_file_to_context(file_path)
                    continue
                elif user_input.startswith('remove '):
                    file_path = user_input[7:].strip()
                    self._remove_file_from_context(file_path)
                    continue
                elif cmd == 'clear':
                    self._clear_context()
                    continue
                
                # Process regular chat message
                response = self._process_chat_message(user_input)
                if response:
                    self.presenter.show_separator()
                    self.presenter.show_header("🤖 MiniMax Response")
                    self.show_markdown(response)
                else:
                    self.show_notification("Failed to get response", level='error')
                
            except KeyboardInterrupt:
                self.show_notification("\nGoodbye! 👋", level='info')
                break
            except EOFError:
                self.show_notification("\nGoodbye! 👋", level='info')
                break
        
        return True
    
    def context(self, args: Any) -> bool:
        """Manage conversation context."""
        action = args.action
        
        if action == 'list':
            self._show_context()
        elif action == 'add' and args.file:
            self._add_file_to_context(args.file)
        elif action == 'remove' and args.file:
            self._remove_file_from_context(args.file)
        elif action == 'clear':
            self._clear_context()
        else:
            self.show_notification("Invalid context action or missing file parameter", level='error')
            return False
        
        return True
    
    def _process_chat_message(self, message: str) -> str:
        """Process a chat message and get AI response."""
        # Build context for the AI
        context_parts: List[str] = []
        
        # Add file contexts
        if self.context_files:
            context_parts.append("=== CONTEXT FILES ===")
            for file_info in self.context_files:
                context_parts.append(f"File: {file_info['path']}")
                context_parts.append(f"Language: {file_info['language']}")
                context_parts.append("Content:")
                context_parts.append(file_info['content'])
                context_parts.append("=" * 30)
        
        # Add conversation history (last 5 exchanges)
        if self.conversation_history:
            context_parts.append("=== RECENT CONVERSATION ===")
            for exchange in self.conversation_history[-5:]:
                context_parts.append(f"User: {exchange['user']}")
                context_parts.append(f"Assistant: {exchange['assistant']}")
                context_parts.append("-" * 20)
        
        # Combine context
        full_context = "\n".join(context_parts) if context_parts else None
        
        # Create the prompt
        prompt = f"""
You are a helpful coding assistant. Please help with the following request:

{message}

Please provide clear, practical advice and code examples when appropriate.
If the request involves code modification, provide specific suggestions.
"""
        
        # Get AI response with streaming through presenter
        response = self.ask_ai(prompt, context=full_context, stream=True)
        
        # Store in conversation history
        if response:
            self.conversation_history.append({
                'user': message,
                'assistant': response
            })
            # Keep only last 10 exchanges
            if len(self.conversation_history) > 10:
                self.conversation_history = self.conversation_history[-10:]
        
        return response
    
    def _add_file_to_context(self, file_path: str) -> bool:
        """Add a file to the conversation context."""
        if not os.path.exists(file_path):
            self.show_notification(f"File not found: {file_path}", level='error')
            return False
        
        # Check if already in context
        for file_info in self.context_files:
            if file_info['path'] == file_path:
                self.show_notification(f"File already in context: {file_path}", level='warning')
                return True
        
        # Read file content
        content = self.read_file(file_path)
        if not content:
            return False
        
        # Add to context
        file_info = {
            'path': file_path,
            'language': self.detect_language(file_path),
            'content': content
        }
        self.context_files.append(file_info)
        self.show_notification(f"Added to context: {file_path}", level='success')
        return True
    
    def _remove_file_from_context(self, file_path: str) -> bool:
        """Remove a file from the conversation context."""
        for i, file_info in enumerate(self.context_files):
            if file_info['path'] == file_path:
                del self.context_files[i]
                self.show_notification(f"Removed from context: {file_path}", level='success')
                return True
        
        self.show_notification(f"File not in context: {file_path}", level='warning')
        return False
    
    def _clear_context(self):
        """Clear all context."""
        self.context_files.clear()
        self.conversation_history.clear()
        self.show_notification("Context cleared", level='info')
    
    def _show_context(self):
        """Show current context."""
        self.presenter.show_header("📋 Current Context")
        
        if self.context_files:
            # Tree structure for context files
            tree_data = {
                "Context Files": [
                    {
                        "name": f"{file_info['path']} ({file_info['language']})",
                        "metadata": {
                            "type": "file",
                            "language": file_info['language'],
                            "path": file_info['path']
                        }
                    }
                    for file_info in self.context_files
                ]
            }
            self.presenter.show_tree(tree_data)
            
            # Table summary for context files
            table_data = [
                {"Path": file_info['path'], "Language": file_info['language']}
                for file_info in self.context_files
            ]
            self.show_table(table_data, title="Context Files Summary")
        else:
            self.show_notification("No files in context", level='info')
        
        self.show_notification(
            f"Conversation history: {len(self.conversation_history)} exchanges",
            level='info'
        )
        self.presenter.show_separator()
    
    def _load_project_context(self, project_dir: str):
        """Load relevant files from a project directory."""
        if not os.path.isdir(project_dir):
            self.show_notification(f"Project directory not found: {project_dir}", level='warning')
            return
        
        # Look for common important files
        important_files = [
            'README.md', 'README.txt',
            'package.json', 'requirements.txt', 'Cargo.toml', 'pom.xml',
            'main.py', 'app.py', 'index.js', 'main.js',
            '.gitignore', 'Dockerfile'
        ]
        
        added_count = 0
        for filename in important_files:
            file_path = os.path.join(project_dir, filename)
            if os.path.exists(file_path):
                if self._add_file_to_context(file_path):
                    added_count += 1
        
        if added_count > 0:
            self.show_notification(f"Loaded {added_count} project files into context", level='success')
        else:
            self.show_notification("No standard project files found", level='info')
    
    def _show_help(self):
        """Show help for interactive commands."""
        help_content = """🔧 **Interactive Commands:**
- `help`              - Show this help
- `context`           - Show current context
- `add <file>`        - Add file to context
- `remove <file>`     - Remove file from context
- `clear`             - Clear all context
- `exit/quit/bye`     - Exit the session

💡 **Tips:**
- Ask questions about your code
- Request code reviews or explanations
- Get help with debugging
- Ask for code generation or modifications
- Context files help the AI understand your project
"""
        self.show_markdown(help_content)