#!/usr/bin/env python3
"""
SAGE CODE REVIEW - Powered by Eden's Evolved Intelligence
Connects verified capabilities to real code review tasks
"""
import sqlite3
import subprocess
import ast
import re
import sys
sys.path.insert(0, '/Eden/CORE/evolved_dna')

DB = "/Eden/DATA/asi_memory.db"
PHI = 1.618033988749895

class SAGEReviewer:
    """Eden-powered code reviewer for SAGE service"""
    
    def __init__(self):
        self.verified_funcs = self.load_verified()
        print(f"🧠 SAGE loaded with {len(self.verified_funcs)} verified capabilities")
    
    def load_verified(self):
        """Load Eden's verified working functions"""
        conn = sqlite3.connect(DB)
        funcs = conn.execute(
            "SELECT id, code FROM caps WHERE id LIKE 'verified_%'"
        ).fetchall()
        conn.close()
        return {name: code for name, code in funcs}
    
    def analyze_code(self, code):
        """Analyze submitted code for issues"""
        issues = []
        suggestions = []
        score = 100
        
        # Check for common issues
        if 'input(' in code:
            issues.append("⚠️ Uses input() - may hang in automated environments")
            score -= 10
        
        if 'eval(' in code or 'exec(' in code:
            issues.append("🚨 SECURITY: Uses eval/exec - potential code injection")
            score -= 25
        
        if 'import os' in code and 'system' in code:
            issues.append("🚨 SECURITY: Shell command execution detected")
            score -= 25
        
        # Check syntax
        try:
            tree = ast.parse(code)
            
            # Count functions and classes
            funcs = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)]
            classes = [n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]
            
            if not funcs and not classes:
                issues.append("💡 No functions or classes defined - consider modularizing")
                score -= 5
            
            # Check for docstrings
            for func in funcs:
                if not ast.get_docstring(func):
                    suggestions.append(f"📝 Add docstring to function '{func.name}'")
            
            # Check for type hints
            for func in funcs:
                if not func.returns and not func.args.args[0].annotation if func.args.args else True:
                    suggestions.append(f"🏷️ Consider adding type hints to '{func.name}'")
            
        except SyntaxError as e:
            issues.append(f"❌ SYNTAX ERROR: {e.msg} at line {e.lineno}")
            score -= 50
        
        # Check complexity
        lines = code.split('\n')
        if len(lines) > 100:
            suggestions.append("📦 Consider splitting into multiple files")
        
        # Check for long functions
        for func in funcs if 'funcs' in dir() else []:
            func_lines = ast.unparse(func).count('\n')
            if func_lines > 30:
                suggestions.append(f"✂️ Function '{func.name}' is long ({func_lines} lines) - consider refactoring")
        
        return {
            "score": max(0, score),
            "issues": issues,
            "suggestions": suggestions,
            "phi_rating": score * PHI / 100
        }
    
    def suggest_improvements(self, code):
        """Use Eden's LLM to suggest improvements"""
        prompt = f"""Review this code and suggest 3 specific improvements:
```python
{code[:2000]}
```

Format:
1. [improvement]
2. [improvement]  
3. [improvement]"""
        
        try:
            r = subprocess.run(
                ["ollama", "run", "eden-coder-omega", prompt],
                capture_output=True, text=True, timeout=60
            )
            return r.stdout.strip()
        except:
            return "Unable to generate suggestions"
    
    def review(self, code):
        """Full SAGE code review"""
        print("\n" + "="*60)
        print("🔍 SAGE CODE REVIEW - Powered by Eden")
        print("="*60)
        
        analysis = self.analyze_code(code)
        
        print(f"\n📊 CODE SCORE: {analysis['score']}/100 (φ: {analysis['phi_rating']:.2f})")
        
        if analysis['issues']:
            print("\n🚨 ISSUES FOUND:")
            for issue in analysis['issues']:
                print(f"   {issue}")
        
        if analysis['suggestions']:
            print("\n💡 SUGGESTIONS:")
            for sug in analysis['suggestions']:
                print(f"   {sug}")
        
        print("\n🧠 EDEN'S RECOMMENDATIONS:")
        improvements = self.suggest_improvements(code)
        print(improvements)
        
        print("\n" + "="*60)
        return analysis


# Demo review
if __name__ == "__main__":
    reviewer = SAGEReviewer()
    
    # Test with sample code
    test_code = '''
def calculate_total(items):
    total = 0
    for item in items:
        total = total + item["price"] * item["quantity"]
    return total

def process_order(order_id):
    import os
    os.system("echo Processing " + order_id)
    items = get_items(order_id)
    return calculate_total(items)
'''
    
    result = reviewer.review(test_code)
    print(f"\n✅ Review complete! Score: {result['score']}/100")
