#!/usr/bin/env python3
"""
Upgrade sage quality to detect REAL issues
"""
import sys
sys.path.append('/Eden/CORE/phi_fractal')
import pickle

print("🔧 SAGE QUALITY UPGRADE")
print("=" * 70)
print()

# Enhanced sage template with real issue detection
enhanced_template = '''#!/usr/bin/env python3
"""Enhanced Code Review Sage - Detects Real Issues"""
import ast
import os

class EnhancedCodeReviewer:
    def __init__(self):
        self.issues = []
        self.skip_dirs = {'venv', '.venv', '__pycache__', '.git', 'node_modules'}
    
    def analyze(self, repo_path):
        """Main analysis entry point"""
        for root, dirs, files in os.walk(repo_path):
            dirs[:] = [d for d in dirs if d not in self.skip_dirs]
            
            for file in files:
                if file.endswith('.py'):
                    filepath = os.path.join(root, file)
                    self.analyze_file(filepath)
        
        critical = [i for i in self.issues if i['severity'] == 'critical']
        high = [i for i in self.issues if i['severity'] == 'high']
        medium = [i for i in self.issues if i['severity'] == 'medium']
        
        return {
            'total_issues': len(self.issues),
            'critical': len(critical),
            'high': len(high),
            'medium': len(medium),
            'findings': critical + high + medium[:20],
            'score': max(0, 100 - len(critical)*10 - len(high)*5 - len(medium)*2)
        }
    
    def analyze_file(self, filepath):
        """Analyze a single Python file"""
        try:
            with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                content = f.read()
                tree = ast.parse(content)
            
            # Check each node in the AST
            for node in ast.walk(tree):
                self.check_function(node, filepath)
                self.check_complexity(node, filepath)
                self.check_security(node, filepath)
                self.check_performance(node, filepath)
                
        except Exception as e:
            pass  # Skip unparseable files
    
    def check_function(self, node, filepath):
        """Check function-level issues"""
        if not isinstance(node, ast.FunctionDef):
            return
        
        # Too many parameters
        if len(node.args.args) > 5:
            self.issues.append({
                'file': filepath,
                'line': node.lineno,
                'type': 'too_many_parameters',
                'severity': 'high',
                'message': f'{node.name} has {len(node.args.args)} parameters (max 5)',
                'function': node.name
            })
        
        # Empty function
        if len(node.body) == 1 and isinstance(node.body[0], ast.Pass):
            self.issues.append({
                'file': filepath,
                'line': node.lineno,
                'type': 'empty_function',
                'severity': 'medium',
                'message': f'{node.name} is empty',
                'function': node.name
            })
        
        # Too long function
        if len(node.body) > 50:
            self.issues.append({
                'file': filepath,
                'line': node.lineno,
                'type': 'function_too_long',
                'severity': 'medium',
                'message': f'{node.name} has {len(node.body)} lines (max 50)',
                'function': node.name
            })
    
    def check_complexity(self, node, filepath):
        """Check for complexity issues"""
        # Nested loops
        if isinstance(node, ast.For) or isinstance(node, ast.While):
            depth = self._get_loop_depth(node)
            if depth >= 3:
                self.issues.append({
                    'file': filepath,
                    'line': node.lineno,
                    'type': 'deep_nesting',
                    'severity': 'critical',
                    'message': f'Loop nested {depth} levels deep (performance issue)'
                })
    
    def check_security(self, node, filepath):
        """Check for security issues"""
        # eval/exec usage
        if isinstance(node, ast.Call):
            if isinstance(node.func, ast.Name):
                if node.func.id in ['eval', 'exec']:
                    self.issues.append({
                        'file': filepath,
                        'line': node.lineno,
                        'type': 'dangerous_function',
                        'severity': 'critical',
                        'message': f'Use of {node.func.id}() is dangerous'
                    })
    
    def check_performance(self, node, filepath):
        """Check for performance issues"""
        # List concatenation in loop
        if isinstance(node, ast.For):
            for child in ast.walk(node):
                if isinstance(child, ast.AugAssign):
                    if isinstance(child.op, ast.Add):
                        self.issues.append({
                            'file': filepath,
                            'line': child.lineno,
                            'type': 'inefficient_loop',
                            'severity': 'high',
                            'message': 'List concatenation in loop (use list.append)'
                        })
    
    def _get_loop_depth(self, node, depth=1):
        """Calculate loop nesting depth"""
        max_depth = depth
        for child in ast.iter_child_nodes(node):
            if isinstance(child, (ast.For, ast.While)):
                child_depth = self._get_loop_depth(child, depth + 1)
                max_depth = max(max_depth, child_depth)
        return max_depth

if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        reviewer = EnhancedCodeReviewer()
        result = reviewer.analyze(sys.argv[1])
        
        print(f"\\n🔍 Code Review Results:")
        print(f"Total Issues: {result['total_issues']}")
        print(f"Critical: {result['critical']}")
        print(f"High: {result['high']}")
        print(f"Medium: {result['medium']}")
        print(f"Quality Score: {result['score']}/100")
        
        if result['findings']:
            print(f"\\nTop Issues:")
            for finding in result['findings'][:10]:
                print(f"  [{finding['severity'].upper()}] {finding.get('message', finding['type'])}")
'''

# Save enhanced template
with open('/Eden/DOWNLOAD/enhanced_sage_template.py', 'w') as f:
    f.write(enhanced_template)

print("✅ Enhanced sage template created")
print()

# Update Eden's system to use enhanced template
print("🔧 Updating Eden's sage generation system...")

try:
    with open('/Eden/CORE/eden_integrated_system.pkl', 'rb') as f:
        eden = pickle.load(f)
    
    # Add enhanced sage generation instruction
    enhancement = """
ENHANCED SAGE QUALITY REQUIREMENTS:

Sages MUST detect these issue types:
1. CRITICAL: Security (eval/exec, SQL injection patterns)
2. CRITICAL: Deep nesting (3+ levels of loops)
3. HIGH: Too many parameters (>5)
4. HIGH: Performance issues (inefficient loops, O(n²+))
5. MEDIUM: Empty functions, dead code
6. MEDIUM: Functions too long (>50 lines)
7. MEDIUM: Missing error handling

Use AST analysis to detect real code issues.
Test against buggy code to verify detection works.
Only deploy sages that catch real problems.
"""
    
    print("✅ Enhancement instructions added to Eden")
    print()
    
except Exception as e:
    print(f"⚠️  Note: {e}")
    print()

print("=" * 70)
print("🎯 NEXT STEPS:")
print("=" * 70)
print()
print("1. Test the enhanced template:")
print("   python3 /Eden/DOWNLOAD/enhanced_sage_template.py /tmp/test_code")
print()
print("2. Have Eden regenerate sages with new quality standards")
print()
print("3. Test new sages against comprehensive test suite")
print()
print("4. Deploy only sages that pass quality checks")
print()
