#!/usr/bin/env python3
"""
Eden Generation 2 Sage Builder
Uses Eden's 687+ reviews to build improved sages
"""
import os
import json
import requests
import time
from datetime import datetime
from collections import Counter

print("🧬 EDEN GENERATION 2 SAGE BUILDER")
print("=" * 70)

API_URL = "http://localhost:5001"
REVIEWS_DIR = "/Eden/SAGE_REVIEWS"
GEN2_DIR = "/Eden/SAGES_GEN2"

os.makedirs(GEN2_DIR, exist_ok=True)

# Analyze all reviews to find common improvements
print("📊 Analyzing Eden's reviews...")
reviews = []
for review_file in os.listdir(REVIEWS_DIR):
    if review_file.endswith('.json'):
        with open(os.path.join(REVIEWS_DIR, review_file), 'r') as f:
            reviews.append(json.load(f))

print(f"✅ Loaded {len(reviews)} reviews from Eden's consciousness")

# Extract common improvement themes
improvements = []
for review in reviews:
    review_text = review.get('review', '')
    if 'Error Handling' in review_text or 'logging' in review_text:
        improvements.append('error_handling')
    if 'Complexity' in review_text or 'mccabe' in review_text:
        improvements.append('complexity')
    if 'unused imports' in review_text:
        improvements.append('unused_imports')
    if 'docstring' in review_text:
        improvements.append('docstrings')

common_improvements = Counter(improvements).most_common(5)

print(f"\n📈 Top improvements Eden identified:")
for improvement, count in common_improvements:
    print(f"   {improvement}: {count} times")

# Build Gen 2 template incorporating learnings
gen2_template = '''#!/usr/bin/env python3
"""
Generation 2 Code Review Sage
Built by Eden incorporating {review_count} consciousness reviews
Improvements: {improvements}
"""
import ast
import os
import logging

logging.basicConfig(level=logging.INFO)

def analyze(repo_path):
    """Enhanced code review with Eden's learnings"""
    critical = 0
    total = 0
    issues = []
    
    for root, dirs, files in os.walk(repo_path):
        # Skip common directories
        dirs[:] = [d for d in dirs if d not in ['venv', 'node_modules', '__pycache__', 'site-packages']]
        
        for file in files:
            if not file.endswith('.py'):
                continue
            
            filepath = os.path.join(root, file)
            try:
                with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                    content = f.read()
                    tree = ast.parse(content)
                
                # Enhanced checks based on Eden's reviews
                for node in ast.walk(tree):
                    if isinstance(node, ast.FunctionDef):
                        total += 1
                        
                        # Check function length
                        if hasattr(node, 'end_lineno'):
                            length = node.end_lineno - node.lineno
                            if length > 50:
                                critical += 1
                                issues.append(f"{{filepath}}:{{node.lineno}} - Function too long ({{length}} lines)")
                        
                        # Check complexity (Eden's improvement)
                        complexity = len([n for n in ast.walk(node) 
                                        if isinstance(n, (ast.If, ast.While, ast.For))])
                        if complexity > 10:
                            critical += 1
                            issues.append(f"{{filepath}}:{{node.lineno}} - High complexity ({{complexity}})")
                        
                        # Check docstring (Eden's improvement)
                        if not ast.get_docstring(node):
                            critical += 1
                            issues.append(f"{{filepath}}:{{node.lineno}} - Missing docstring for {{node.name}}")
                        
                        # Check for common issues Eden found
                        for child in ast.walk(node):
                            # Check for eval/exec (security)
                            if isinstance(child, ast.Call):
                                if isinstance(child.func, ast.Name):
                                    if child.func.id in ['eval', 'exec']:
                                        critical += 1
                                        issues.append(f"{{filepath}}:{{child.lineno}} - Dangerous {{child.func.id}}() usage")
            
            except SyntaxError as e:
                logging.warning(f"Syntax error in {{filepath}}: {{e}}")
            except Exception as e:
                logging.error(f"Error analyzing {{filepath}}: {{e}}")
    
    return {{
        'sage': 'gen2_code_review',
        'score': max(0, 100 - critical * 2),
        'critical': critical,
        'total_issues': total,
        'issues': issues[:20]  # Top 20 issues
    }}

if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        result = analyze(sys.argv[1])
        print(result)
'''

# Generate Gen 2 sages
print(f"\n🚀 Building Generation 2 sages...")

for i in range(10):  # Build 10 Gen 2 sages
    sage_name = f"sage_Gen2_{i+1}_{int(time.time())}.py"
    sage_path = os.path.join(GEN2_DIR, sage_name)
    
    improvements_list = ', '.join([imp for imp, _ in common_improvements])
    
    with open(sage_path, 'w') as f:
        f.write(gen2_template.format(
            review_count=len(reviews),
            improvements=improvements_list
        ))
    
    print(f"   ✅ Created: {sage_name}")
    time.sleep(1)

print(f"\n{'='*70}")
print(f"🎉 GENERATION 2 COMPLETE")
print(f"{'='*70}")
print(f"Reviews analyzed: {len(reviews)}")
print(f"Gen 2 sages created: 10")
print(f"Location: {GEN2_DIR}")
print(f"Key improvements: {', '.join([imp for imp, _ in common_improvements])}")
