"""
Code analysis commands for the MiniMax Code CLI.

Provides commands for reviewing, explaining, debugging, and optimizing code.
"""

import os
from typing import Any, List

from .base import BaseCommand


class AnalyzeCommands(BaseCommand):
    """Commands for analyzing code files and projects."""
    
    def __init__(self, client, config, presenter):
        """Initialize analyze commands with presenter integration."""
        super().__init__(client, config, presenter)
    
    def review(self, args: Any) -> bool:
        """Review code files for issues and improvements."""
        self.show_notification(f"Starting review of {len(args.files)} file(s)...", "info")
        
        all_results = []
        
        for file_path in args.files:
            if not os.path.exists(file_path):
                self.print_error(f"File not found: {file_path}")
                continue
            
            self.show_notification(f"Analyzing {file_path}...", "info")
            
            # Read the file
            code = self.read_file(file_path)
            if not code:
                continue
            
            # Detect language
            language = self.detect_language(file_path)
            
            # Create focus instruction
            focus_instruction = ""
            if args.focus:
                focus_instruction = f"Focus particularly on {args.focus} aspects."
            
            # Enhanced prompt for structured output
            prompt = f"""
Please review the following {language} code and provide feedback in a structured format.

{focus_instruction}

For each issue found, provide:
1. Issue type/category
2. Severity level (Critical/High/Medium/Low)
3. Line number (if applicable)
4. Description of the issue
5. Specific suggestion for improvement

Code:
{code}

Please format your response as a structured analysis with clear sections for:
- **Code Quality Issues**
- **Security Concerns** 
- **Performance Opportunities**
- **Best Practice Recommendations**

Use markdown formatting with code blocks for examples.
"""
            
            # Get AI response
            response = self.ask_ai(prompt)
            if response:
                # Display file header
                self.presenter.show_header(f"📋 Review Results: {file_path}")
                
                # Show the original code with syntax highlighting
                self.show_code(code, language, title=f"Source Code: {file_path}")
                
                # Display the structured review as markdown
                self.show_markdown(response)
                
                # Parse response for table display (simplified parsing)
                issues_data = self._parse_review_response(response, file_path)
                if issues_data:
                    self.show_table(
                        issues_data,
                        title="📊 Issues Summary",
                        show_header=True
                    )
                
                all_results.append({
                    'file': file_path,
                    'language': language,
                    'issues_found': len(issues_data)
                })
                
                self.presenter.show_separator()
            else:
                self.print_error(f"Failed to analyze {file_path}")
        
        # Show summary table
        if all_results:
            self.show_table(
                all_results,
                title="📈 Review Summary",
                show_header=True
            )
        
        return True
    
    def explain(self, args: Any) -> bool:
        """Explain how code works."""
        file_path = args.file
        
        if not os.path.exists(file_path):
            self.print_error(f"File not found: {file_path}")
            return False
        
        self.show_notification(f"Generating explanation for {file_path}...", "info")
        
        # Read the file or specific lines
        if args.lines:
            code = self.get_lines_from_file(file_path, args.lines)
            if not code:
                self.print_error(f"Could not extract lines {args.lines} from {file_path}")
                return False
        else:
            code = self.read_file(file_path)
            if not code:
                return False
        
        # If specific function requested, try to extract it
        if args.function:
            # This is a simplified function extraction
            # In a real implementation, you'd use AST parsing
            lines = code.split('\n')
            function_lines = []
            in_function = False
            indent_level = 0
            
            for line in lines:
                if f"def {args.function}" in line or f"function {args.function}" in line:
                    in_function = True
                    indent_level = len(line) - len(line.lstrip())
                    function_lines.append(line)
                elif in_function:
                    current_indent = len(line) - len(line.lstrip())
                    if line.strip() and current_indent <= indent_level:
                        break
                    function_lines.append(line)
            
            if function_lines:
                code = '\n'.join(function_lines)
            else:
                self.print_warning(f"Function '{args.function}' not found, explaining entire file")
        
        # Detect language
        language = self.detect_language(file_path)
        
        # Enhanced explanation prompt for markdown output
        prompt = f"""
Please provide a comprehensive explanation of the following {language} code.

Structure your explanation using markdown formatting with the following sections:

## 📋 Overview
Brief summary of what this code does

## 🔧 How It Works
Step-by-step explanation of the logic and flow

## 🏗️ Key Components
Description of important functions, classes, or variables

## 💡 Patterns & Techniques
Notable programming patterns or techniques used

## 🔍 Code Walkthrough
Line-by-line or block-by-block analysis with code examples

Code to explain:
```{language}
{code}
```

Use code blocks, bullet points, and clear headings to make the explanation educational and easy to follow.
"""
        
        # Get AI response
        response = self.ask_ai(prompt)
        if response:
            # Build header text
            header_parts = [f"📖 Code Explanation: {file_path}"]
            if args.function:
                header_parts.append(f"Function: {args.function}")
            if args.lines:
                header_parts.append(f"Lines: {args.lines}")
            
            header_text = " - ".join(header_parts)
            self.presenter.show_header(header_text)
            
            # Show the code being explained with syntax highlighting
            code_title = f"Code Being Explained"
            if args.function:
                code_title += f" - {args.function}()"
            if args.lines:
                code_title += f" (Lines {args.lines})"
                
            self.show_code(code, language, title=code_title)
            
            # Display the explanation as formatted markdown
            self.show_markdown(response)
            
            self.presenter.show_separator()
            return True
        else:
            self.print_error("Failed to generate explanation")
            return False
    
    def debug(self, args: Any) -> bool:
        """Help debug code issues."""
        file_path = args.file
        
        if not os.path.exists(file_path):
            self.print_error(f"File not found: {file_path}")
            return False
        
        self.show_notification(f"Analyzing debug issues in {file_path}...", "info")
        
        # Read the file
        code = self.read_file(file_path)
        if not code:
            return False
        
        # Detect language
        language = self.detect_language(file_path)
        
        # Prepare error information
        error_info = ""
        if args.error:
            error_info += f"Error message: {args.error}\n"
        if args.context:
            error_info += f"Additional context: {args.context}\n"
        
        if not error_info:
            error_info = "Please analyze this code for potential issues."
        
        # Enhanced debugging prompt for structured output
        prompt = f"""
Please help debug the following {language} code and provide a structured analysis.

{error_info}

For your analysis, please provide:

## 🔍 Issue Analysis
Identify the likely cause(s) of the problem

## 🛠️ Proposed Solutions
Specific fixes with code examples

## 📝 Explanation
Why the issue occurred and how the fix addresses it

## ✅ Prevention
How to avoid similar issues in the future

Code to debug:
```{language}
{code}
```

If you provide corrected code, use proper code blocks with syntax highlighting.
Structure your response using markdown formatting for clarity.
"""
        
        # Get AI response
        response = self.ask_ai(prompt)
        if response:
            self.presenter.show_header(f"🐛 Debug Analysis: {file_path}")
            
            # Show error context if provided
            if args.error or args.context:
                context_data = []
                if args.error:
                    context_data.append({"Type": "Error Message", "Details": args.error})
                if args.context:
                    context_data.append({"Type": "Context", "Details": args.context})
                
                self.show_table(
                    context_data,
                    title="🚨 Debug Context",
                    show_header=True
                )
            
            # Show the problematic code
            self.show_code(code, language, title="Code Under Analysis")
            
            # Display the debug analysis as markdown
            self.show_markdown(response)
            
            # Parse and show debug findings in table format
            debug_data = self._parse_debug_response(response, file_path)
            if debug_data:
                self.show_table(
                    debug_data,
                    title="🔧 Debug Findings",
                    show_header=True
                )
            
            self.presenter.show_separator()
            return True
        else:
            self.print_error("Failed to generate debug analysis")
            return False
    
    def optimize(self, args: Any) -> bool:
        """Suggest code optimizations."""
        file_path = args.file
        
        if not os.path.exists(file_path):
            self.print_error(f"File not found: {file_path}")
            return False
        
        self.show_notification(f"Analyzing optimization opportunities in {file_path}...", "info")
        
        # Read the file
        code = self.read_file(file_path)
        if not code:
            return False
        
        # Detect language
        language = self.detect_language(file_path)
        
        # Determine optimization target
        target = args.target or "general performance and readability"
        
        # Enhanced optimization prompt for structured output
        prompt = f"""
Please analyze the following {language} code for optimization opportunities targeting: {target}

Provide a comprehensive optimization analysis with the following structure:

## 🎯 Optimization Target
{target}

## 📊 Current Analysis
Assessment of the current code's performance and structure

## ⚡ Optimization Opportunities
Specific areas that can be improved with explanations

## 🔧 Optimized Code
Provide the improved version with clear improvements highlighted

## 📈 Expected Benefits
Quantify the improvements (performance, readability, maintainability)

## ⚖️ Trade-offs
Any potential downsides or considerations

Original code:
```{language}
{code}
```

Use markdown formatting and code blocks for clear presentation.
"""
        
        # Get AI response
        response = self.ask_ai(prompt)
        if response:
            self.presenter.show_header(f"⚡ Optimization Analysis: {file_path}")
            
            # Show optimization target info
            target_data = [{"Optimization Target": target, "Language": language, "File": file_path}]
            self.show_table(
                target_data,
                title="🎯 Optimization Parameters",
                show_header=True
            )
            
            # Show original code
            self.show_code(code, language, title="Original Code")
            
            # Display optimization analysis as markdown
            self.show_markdown(response)
            
            # Parse and show optimization opportunities in table format
            optimization_data = self._parse_optimization_response(response, target)
            if optimization_data:
                self.show_table(
                    optimization_data,
                    title="📈 Optimization Summary",
                    show_header=True
                )
            
            self.presenter.show_separator()
            
            # Ask if user wants to apply optimizations
            if self.confirm_action("Would you like to save the optimized version?"):
                self.show_notification("To apply optimizations, use the 'edit modify' command with the suggested changes.", "info")
            
            return True
        else:
            self.print_error("Failed to generate optimization suggestions")
            return False
    
    def _parse_review_response(self, response: str, file_path: str) -> List[dict]:
        """Parse AI review response to extract structured issue data."""
        # Simplified parsing - in a real implementation, you'd use more sophisticated parsing
        issues = []
        lines = response.split('\n')
        
        # Look for common issue patterns
        issue_keywords = ['error', 'warning', 'issue', 'problem', 'bug', 'vulnerability']
        severity_keywords = {'critical': 'Critical', 'high': 'High', 'medium': 'Medium', 'low': 'Low'}
        
        for i, line in enumerate(lines):
            line_lower = line.lower()
            if any(keyword in line_lower for keyword in issue_keywords):
                # Extract basic issue info
                severity = 'Medium'  # Default
                for sev_key, sev_val in severity_keywords.items():
                    if sev_key in line_lower:
                        severity = sev_val
                        break
                
                issues.append({
                    'Issue': line.strip('- *#').strip()[:50] + '...' if len(line.strip()) > 50 else line.strip('- *#').strip(),
                    'Severity': severity,
                    'Line': 'N/A',  # Would need more sophisticated parsing
                    'File': os.path.basename(file_path),
                    'Category': 'General'
                })
        
        # If no issues found through parsing, create a summary entry
        if not issues:
            issues.append({
                'Issue': 'Analysis completed',
                'Severity': 'Info',
                'Line': 'N/A',
                'File': os.path.basename(file_path),
                'Category': 'Summary'
            })
        
        return issues[:10]  # Limit to 10 issues for display
    
    def _parse_debug_response(self, response: str, file_path: str) -> List[dict]:
        """Parse AI debug response to extract structured findings."""
        findings = []
        
        # Look for solution patterns
        if 'solution' in response.lower() or 'fix' in response.lower():
            findings.append({
                'Finding': 'Solution provided',
                'Type': 'Fix',
                'Priority': 'High',
                'File': os.path.basename(file_path)
            })
        
        if 'cause' in response.lower() or 'reason' in response.lower():
            findings.append({
                'Finding': 'Root cause identified',
                'Type': 'Analysis',
                'Priority': 'High',
                'File': os.path.basename(file_path)
            })
        
        if 'prevent' in response.lower():
            findings.append({
                'Finding': 'Prevention strategies provided',
                'Type': 'Prevention',
                'Priority': 'Medium',
                'File': os.path.basename(file_path)
            })
        
        return findings
    
    def _parse_optimization_response(self, response: str, target: str) -> List[dict]:
        """Parse AI optimization response to extract structured opportunities."""
        opportunities = []
        
        # Look for optimization patterns
        if 'performance' in response.lower():
            opportunities.append({
                'Opportunity': 'Performance improvements identified',
                'Target': target,
                'Impact': 'High',
                'Effort': 'Medium'
            })
        
        if 'memory' in response.lower():
            opportunities.append({
                'Opportunity': 'Memory optimization available',
                'Target': target,
                'Impact': 'Medium',
                'Effort': 'Low'
            })
        
        if 'readability' in response.lower() or 'clean' in response.lower():
            opportunities.append({
                'Opportunity': 'Code readability enhancements',
                'Target': target,
                'Impact': 'Medium',
                'Effort': 'Low'
            })
        
        return opportunities
