File size: 6,043 Bytes
ec37394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"""πŸ€– 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": ""}