#!/usr/bin/env python3
"""
Code Assistant Bot - AI-powered coding assistant
Author: RSK World (https://rskworld.in)
Founder: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

from flask import Flask, render_template, request, jsonify, session
from flask_cors import CORS
from openai import OpenAI
import os
import re
import json
from datetime import datetime
import logging
from utils.code_analyzer import CodeAnalyzer
from utils.github_integration import GitHubIntegration
from utils.syntax_checker import SyntaxChecker
from utils.code_optimizer import CodeOptimizer
from utils.code_converter import CodeConverter
from utils.code_tester import CodeTester
from utils.code_formatter import CodeFormatter
from utils.code_documenter import CodeDocumenter
from utils.code_reviewer import CodeReviewer
from utils.code_comparator import CodeComparator

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', 'your-secret-key-here')
CORS(app)

# Initialize OpenAI client
openai_api_key = os.environ.get('OPENAI_API_KEY')
if not openai_api_key:
    logger.warning("OPENAI_API_KEY not set. OpenAI features will not work.")
openai_client = OpenAI(api_key=openai_api_key) if openai_api_key else None

# Initialize utility classes
code_analyzer = CodeAnalyzer()
github_integration = GitHubIntegration()
syntax_checker = SyntaxChecker()
code_optimizer = CodeOptimizer()
code_converter = CodeConverter()
code_tester = CodeTester()
code_formatter = CodeFormatter()
code_documenter = CodeDocumenter()
code_reviewer = CodeReviewer()
code_comparator = CodeComparator()

class CodeAssistantBot:
    """
    Main Code Assistant Bot class for handling code generation,
    debugging, explanations, and programming assistance.
    """
    
    def __init__(self):
        self.supported_languages = [
            'python', 'javascript', 'java', 'cpp', 'c', 'csharp',
            'php', 'ruby', 'go', 'rust', 'typescript', 'html', 'css'
        ]
        self.max_code_length = 10000
        
    def generate_code(self, prompt, language='python'):
        """
        Generate code based on user prompt and specified language
        """
        try:
            if not openai_client:
                return "Error: OpenAI API key not configured. Please set OPENAI_API_KEY environment variable."
            
            system_prompt = f"""
            You are an expert programmer and coding assistant. Generate clean, 
            efficient, and well-commented {language} code based on the user's request.
            Follow best practices and include error handling where appropriate.
            """
            
            response = openai_client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=1500,
                temperature=0.7
            )
            
            return response.choices[0].message.content.strip()
            
        except Exception as e:
            logger.error(f"Error generating code: {str(e)}")
            return f"Error generating code: {str(e)}"
    
    def debug_code(self, code, language='python', error_message=None):
        """
        Debug code and provide suggestions for fixing issues
        """
        try:
            if not openai_client:
                return "Error: OpenAI API key not configured. Please set OPENAI_API_KEY environment variable."
            
            system_prompt = f"""
            You are an expert debugging assistant. Analyze the provided {language} code
            and identify any bugs, issues, or potential improvements. 
            Provide clear explanations and corrected code.
            """
            
            user_prompt = f"Code to debug:\n\n{code}"
            if error_message:
                user_prompt += f"\n\nError message: {error_message}"
            
            response = openai_client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt}
                ],
                max_tokens=1500,
                temperature=0.3
            )
            
            return response.choices[0].message.content.strip()
            
        except Exception as e:
            logger.error(f"Error debugging code: {str(e)}")
            return f"Error debugging code: {str(e)}"
    
    def explain_code(self, code, language='python'):
        """
        Provide detailed explanation of the provided code
        """
        try:
            if not openai_client:
                return "Error: OpenAI API key not configured. Please set OPENAI_API_KEY environment variable."
            
            system_prompt = f"""
            You are an expert programming instructor. Explain the provided {language} code
            in detail, including its purpose, logic, and key concepts. Make it easy to understand
            for developers of different skill levels.
            """
            
            response = openai_client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": f"Explain this code:\n\n{code}"}
                ],
                max_tokens=1000,
                temperature=0.5
            )
            
            return response.choices[0].message.content.strip()
            
        except Exception as e:
            logger.error(f"Error explaining code: {str(e)}")
            return f"Error explaining code: {str(e)}"

# Initialize the bot
bot = CodeAssistantBot()

@app.route('/')
def index():
    """
    Main page - Code Assistant Bot interface
    """
    return render_template('index.html')

@app.route('/api/generate', methods=['POST'])
def generate_code():
    """
    API endpoint for code generation
    """
    try:
        data = request.get_json()
        prompt = data.get('prompt', '')
        language = data.get('language', 'python')
        
        if not prompt:
            return jsonify({'error': 'Prompt is required'}), 400
        
        if language not in bot.supported_languages:
            return jsonify({'error': f'Language {language} not supported'}), 400
        
        result = bot.generate_code(prompt, language)
        
        return jsonify({
            'success': True,
            'result': result,
            'language': language,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in generate_code: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/debug', methods=['POST'])
def debug_code():
    """
    API endpoint for code debugging
    """
    try:
        data = request.get_json()
        code = data.get('code', '')
        language = data.get('language', 'python')
        error_message = data.get('error_message', None)
        
        if not code:
            return jsonify({'error': 'Code is required'}), 400
        
        result = bot.debug_code(code, language, error_message)
        
        return jsonify({
            'success': True,
            'result': result,
            'language': language,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in debug_code: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/explain', methods=['POST'])
def explain_code():
    """
    API endpoint for code explanation
    """
    try:
        data = request.get_json()
        code = data.get('code', '')
        language = data.get('language', 'python')
        
        if not code:
            return jsonify({'error': 'Code is required'}), 400
        
        result = bot.explain_code(code, language)
        
        return jsonify({
            'success': True,
            'result': result,
            'language': language,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in explain_code: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/syntax-check', methods=['POST'])
def syntax_check():
    """
    API endpoint for syntax checking
    """
    try:
        data = request.get_json()
        code = data.get('code', '')
        language = data.get('language', 'python')
        
        if not code:
            return jsonify({'error': 'Code is required'}), 400
        
        result = syntax_checker.check_syntax(code, language)
        
        return jsonify({
            'success': True,
            'result': result,
            'language': language,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in syntax_check: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/analyze', methods=['POST'])
def analyze_code():
    """
    API endpoint for code analysis
    """
    try:
        data = request.get_json()
        code = data.get('code', '')
        language = data.get('language', 'python')
        
        if not code:
            return jsonify({'error': 'Code is required'}), 400
        
        result = code_analyzer.analyze(code, language)
        
        return jsonify({
            'success': True,
            'result': result,
            'language': language,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in analyze_code: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/github/search', methods=['POST'])
def github_search():
    """
    API endpoint for GitHub repository search
    """
    try:
        data = request.get_json()
        query = data.get('query', '')
        language = data.get('language', None)
        
        if not query:
            return jsonify({'error': 'Query is required'}), 400
        
        result = github_integration.search_repositories(query, language)
        
        return jsonify({
            'success': True,
            'result': result,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in github_search: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/languages')
def get_supported_languages():
    """
    Get list of supported programming languages
    """
    return jsonify({
        'success': True,
        'languages': bot.supported_languages
    })

@app.route('/api/optimize', methods=['POST'])
def optimize_code():
    """
    API endpoint for code optimization
    """
    try:
        data = request.get_json()
        code = data.get('code', '')
        language = data.get('language', 'python')
        optimization_types = data.get('optimization_types', ['performance', 'readability', 'best_practices'])
        
        if not code:
            return jsonify({'error': 'Code is required'}), 400
        
        result = code_optimizer.optimize_code(code, language, optimization_types)
        
        return jsonify({
            'success': True,
            'result': result,
            'language': language,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in optimize_code: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/convert', methods=['POST'])
def convert_code():
    """
    API endpoint for code conversion between languages
    """
    try:
        data = request.get_json()
        code = data.get('code', '')
        from_lang = data.get('from_language', 'python')
        to_lang = data.get('to_language', 'javascript')
        
        if not code:
            return jsonify({'error': 'Code is required'}), 400
        
        result = code_converter.convert_code(code, from_lang, to_lang)
        
        return jsonify({
            'success': True,
            'result': result,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in convert_code: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/test', methods=['POST'])
def test_code():
    """
    API endpoint for code testing
    """
    try:
        data = request.get_json()
        code = data.get('code', '')
        language = data.get('language', 'python')
        test_type = data.get('test_type', 'syntax')
        test_cases = data.get('test_cases', [])
        
        if not code:
            return jsonify({'error': 'Code is required'}), 400
        
        result = code_tester.test_code(code, language, test_type, test_cases)
        
        return jsonify({
            'success': True,
            'result': result,
            'language': language,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in test_code: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/detect-language', methods=['POST'])
def detect_language():
    """
    API endpoint for detecting programming language
    """
    try:
        data = request.get_json()
        code = data.get('code', '')
        
        if not code:
            return jsonify({'error': 'Code is required'}), 400
        
        detected_language = code_converter.detect_language(code)
        
        return jsonify({
            'success': True,
            'detected_language': detected_language,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in detect_language: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/supported-conversions')
def get_supported_conversions():
    """
    Get list of supported language conversions
    """
    return jsonify({
        'success': True,
        'conversions': code_converter.get_supported_conversions()
    })

@app.route('/api/format', methods=['POST'])
def format_code():
    """
    API endpoint for code formatting
    """
    try:
        data = request.get_json()
        code = data.get('code', '')
        language = data.get('language', 'python')
        style = data.get('style', 'standard')
        
        if not code:
            return jsonify({'error': 'Code is required'}), 400
        
        result = code_formatter.format_code(code, language, style)
        
        return jsonify({
            'success': result.get('success', True),
            'result': result,
            'language': language,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in format_code: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/document', methods=['POST'])
def document_code():
    """
    API endpoint for code documentation generation
    """
    try:
        data = request.get_json()
        code = data.get('code', '')
        language = data.get('language', 'python')
        doc_style = data.get('doc_style', 'standard')
        
        if not code:
            return jsonify({'error': 'Code is required'}), 400
        
        result = code_documenter.generate_documentation(code, language, doc_style)
        
        return jsonify({
            'success': result.get('success', True),
            'result': result,
            'language': language,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in document_code: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/review', methods=['POST'])
def review_code():
    """
    API endpoint for code review
    """
    try:
        data = request.get_json()
        code = data.get('code', '')
        language = data.get('language', 'python')
        
        if not code:
            return jsonify({'error': 'Code is required'}), 400
        
        result = code_reviewer.review_code(code, language)
        
        return jsonify({
            'success': result.get('success', True),
            'result': result,
            'language': language,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in review_code: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/compare', methods=['POST'])
def compare_code():
    """
    API endpoint for code comparison
    """
    try:
        data = request.get_json()
        code1 = data.get('code1', '')
        code2 = data.get('code2', '')
        language = data.get('language', 'auto')
        
        if not code1 or not code2:
            return jsonify({'error': 'Both code snippets are required'}), 400
        
        result = code_comparator.compare_code(code1, code2, language)
        
        return jsonify({
            'success': result.get('success', True),
            'result': result,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error in compare_code: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/health')
def health_check():
    """
    Health check endpoint
    """
    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.now().isoformat(),
        'version': '1.0.0'
    })

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    debug = os.environ.get('FLASK_ENV', 'development') == 'development'
    
    logger.info(f"Starting Code Assistant Bot on port {port}")
    app.run(host='0.0.0.0', port=port, debug=debug)
else:
    # Production deployment (WSGI)
    port = int(os.environ.get('PORT', 5000))
    debug = os.environ.get('FLASK_ENV', 'development') == 'development'
