"""🤖 Google Gemini API Client for AI Features""" import google.generativeai as genai import os import logging from typing import List, Dict, Any from src.config import Config logger = logging.getLogger(__name__) # Configure API key if Config.GOOGLE_API_KEY: genai.configure(api_key=Config.GOOGLE_API_KEY) else: logger.warning("GOOGLE_API_KEY not configured - AI features will be unavailable") async def generate_fixes( code: str, issues: List[Dict[str, Any]], language: str ) -> List[Dict[str, Any]]: """ Generate fix suggestions using Gemini AI. Args: code: Original source code issues: List of issues from linting language: Programming language Returns: List of fix suggestions with explanations """ try: if not Config.GOOGLE_API_KEY: return [{ "issue": "AI service unavailable", "explanation": "GOOGLE_API_KEY not configured", "fix": "Please set your API key in .env file" }] # Initialize model model = genai.GenerativeModel("gemini-1.5-flash") # Build prompt with top issues issues_summary = "\n".join([ f"- Line {issue.get('location', {}).get('row', '?')}: {issue.get('message', 'Unknown issue')}" for issue in issues[:5] # Limit to first 5 ]) prompt = f"""You are a code analysis expert. Given this {language} code with linting issues, suggest specific fixes. CODE: ```{language} {code} ``` ISSUES FOUND: {issues_summary} For each issue, provide: 1. Brief explanation of the problem 2. Concrete fix (code snippet) 3. Why this fix improves the code Format as JSON array with keys: issue, explanation, fix, benefit""" # Generate response response = model.generate_content(prompt) # Parse response text suggestions_text = response.text # Create structured suggestions suggestions = [] for issue in issues[:3]: # Top 3 issues suggestions.append({ "issue": issue.get("message", "Unknown"), "line": issue.get("location", {}).get("row"), "explanation": f"AI-powered fix suggestion available", "fix": suggestions_text[:500], # First 500 chars "ai_response": suggestions_text }) return suggestions except Exception as e: logger.error(f"Gemini API error: {e}", exc_info=True) return [{ "issue": "AI service error", "explanation": f"Failed to generate suggestions: {str(e)}", "fix": "Manual review recommended" }] async def explain_code_with_ai(code: str, question: str, language: str) -> Dict[str, Any]: """🏆 AI-powered code explanation""" try: if not Config.GOOGLE_API_KEY: return { "error": "GOOGLE_API_KEY not configured", "explanation": "Please set your API key to use AI features" } model = genai.GenerativeModel("gemini-1.5-flash") prompt = f"""Explain this {language} code in detail: ```{language} {code} ``` {"Specific question: " + question if question else "Provide a comprehensive explanation covering:"} - What the code does - Key algorithms and logic - Potential improvements - Edge cases to consider Format as markdown with code examples where helpful.""" response = model.generate_content(prompt) return { "explanation": response.text, "language": language, "has_examples": True } except Exception as e: logger.error(f"Code explanation failed: {e}") return {"error": str(e), "explanation": ""} async def generate_tests_with_ai(code: str, framework: str, language: str) -> Dict[str, Any]: """🏆 AI-powered test generation""" try: if not Config.GOOGLE_API_KEY: return { "error": "GOOGLE_API_KEY not configured", "test_code": "# Please configure GOOGLE_API_KEY" } model = genai.GenerativeModel("gemini-1.5-pro") # Use Pro for better code generation prompt = f"""Generate comprehensive {framework} tests for this {language} code: ```{language} {code} ``` Requirements: - Test happy path and edge cases - Include setup/teardown if needed - Add descriptive test names - Cover error handling - Use proper assertions Return ONLY the test code, properly formatted.""" response = model.generate_content(prompt) return { "test_code": response.text, "framework": framework, "language": language } except Exception as e: logger.error(f"Test generation failed: {e}") return {"error": str(e), "test_code": ""} async def generate_docs_with_ai(code: str, style: str, language: str) -> Dict[str, Any]: """🏆 AI-powered documentation generation""" try: if not Config.GOOGLE_API_KEY: return { "error": "GOOGLE_API_KEY not configured", "documentation": "# Please configure GOOGLE_API_KEY" } model = genai.GenerativeModel("gemini-1.5-pro") prompt = f"""Generate {style}-style documentation for this {language} code: ```{language} {code} ``` Include: - Module/function/class docstrings - Parameter descriptions with types - Return value documentation - Usage examples - Raises/Exceptions documentation Return the code WITH documentation added.""" response = model.generate_content(prompt) return { "documented_code": response.text, "style": style, "language": language } except Exception as e: logger.error(f"Documentation generation failed: {e}") return {"error": str(e), "documentation": ""}