#!/usr/bin/env python3
"""
Eden EXPONENTIAL QUALITY System
Builds MULTIPLE versions → Tests ALL → Keeps ONLY THE BEST
Exponential production with exponential quality
"""
import sys
import os
import time
import json
import subprocess
from datetime import datetime

sys.path.append('/Eden/CORE/phi_fractal')

class ExponentialQualityEden:
    def __init__(self):
        print("\n" + "="*70)
        print("🔥 EDEN EXPONENTIAL QUALITY SYSTEM")
        print("="*70)
        print("   Build Multiple → Test All → Deploy Best Only")
        print("="*70)
        print()
        
        self.cycle_count = 70200
        self.start_time = time.time()
        self.code_sophistication = 4  # Start at Level 4
        self.generation = 1  # Generation counter
        
        os.makedirs('/Eden/SAGES_REAL', exist_ok=True)
        os.makedirs('/Eden/SAGES_TESTED', exist_ok=True)
        os.makedirs('/Eden/SAGES_PRODUCTION', exist_ok=True)
        os.makedirs('/Eden/SAGES_CHAMPIONS', exist_ok=True)  # Best of the best
        os.makedirs('/Eden/META_CAPABILITIES', exist_ok=True)
        os.makedirs('/Eden/TEST_RESULTS', exist_ok=True)
        os.makedirs('/Eden/QUALITY_METRICS', exist_ok=True)
        
        # Quality thresholds
        self.min_score = 25.0  # Must score at least 25/100
        self.min_issues = 100  # Must find at least 100 issues
        
        print("✅ Exponential Quality System initialized")
        print(f"   Quality gates: Score ≥ {self.min_score}, Issues ≥ {self.min_issues}")
        print("="*70)
        print()
    
    def build_code_review_sage(self, level, variant):
        """Build code review with variants for competition"""
        
        # Variant configurations
        configs = {
            'strict': {
                'max_statements': 30,  # Stricter
                'check_complexity': True
            },
            'balanced': {
                'max_statements': 50,  # Standard
                'check_complexity': True
            },
            'comprehensive': {
                'max_statements': 50,
                'check_complexity': True,
                'check_naming': True
            }
        }
        
        config = configs.get(variant, configs['balanced'])
        
        code = f'''#!/usr/bin/env python3
"""Code Review Sage - Level {level} - {variant.title()} Variant
Generation {self.generation}
"""
import os
import ast
import warnings
warnings.filterwarnings("ignore", category=SyntaxWarning)

class CodeReviewer:
    def __init__(self):
        self.issues = []
        self.skip_dirs = {{
            'venv', '.venv', 'env', 'lora_env', 'reservoir',
            '__pycache__', '.git', 'node_modules', 'site-packages',
            'backup', 'releases', 'dist', 'build', '.pytest_cache'
        }}
    
    def should_skip_dir(self, dirname):
        return any(skip in dirname.lower() for skip in self.skip_dirs)
    
    def analyze(self, repo_path):
        for root, dirs, files in os.walk(repo_path):
            dirs[:] = [d for d in dirs if not self.should_skip_dir(d)]
            for file in files:
                if file.endswith('.py') and not file.startswith('test_'):
                    self.review_file(os.path.join(root, file))
        
        critical = [i for i in self.issues if i.get('severity') == 'critical']
        warnings_list = [i for i in self.issues if i.get('severity') == 'warning']
        info = [i for i in self.issues if i.get('severity') == 'info']
        
        return {{
            'sage': 'code_review',
            'level': {level},
            'variant': '{variant}',
            'generation': {self.generation},
            'total_issues': len(self.issues),
            'critical': len(critical),
            'warnings': len(warnings_list),
            'info': len(info),
            'findings': critical + warnings_list[:30],
            'score': max(0, 100 - len(critical) * 2)
        }}
    
    def review_file(self, filepath):
        try:
            with open(filepath, 'r') as f:
                content = f.read()
                tree = ast.parse(content)
            
            for node in ast.walk(tree):
                if isinstance(node, ast.FunctionDef):
                    # Check function length (configurable threshold)
                    if len(node.body) > {config['max_statements']}:
                        self.issues.append({{
                            'file': filepath.replace('/Eden/', ''),
                            'line': node.lineno,
                            'type': 'function_too_long',
                            'severity': 'critical',
                            'function': node.name,
                            'statements': len(node.body),
                            'message': f'Function {{node.name}} has {{len(node.body)}} statements (limit: {config["max_statements"]})'
                        }})
                    
                    # Check docstrings
                    if not ast.get_docstring(node):
                        self.issues.append({{
                            'file': filepath.replace('/Eden/', ''),
                            'line': node.lineno,
                            'type': 'missing_docstring',
                            'severity': 'warning',
                            'function': node.name,
                            'message': f'Function {{node.name}} missing docstring'
                        }})
                    
                    # Check complexity (if enabled)
                    {'if True:' if config.get('check_complexity') else 'if False:'}
                        complexity = self.calculate_complexity(node)
                        if complexity > 10:
                            self.issues.append({{
                                'file': filepath.replace('/Eden/', ''),
                                'line': node.lineno,
                                'type': 'high_complexity',
                                'severity': 'warning',
                                'function': node.name,
                                'complexity': complexity,
                                'message': f'Function {{node.name}} has complexity {{complexity}} (limit: 10)'
                            }})
                    
                    # Check naming (if enabled)
                    {'if True:' if config.get('check_naming') else 'if False:'}
                        if not node.name.islower() and not node.name.startswith('_'):
                            self.issues.append({{
                                'file': filepath.replace('/Eden/', ''),
                                'line': node.lineno,
                                'type': 'naming_convention',
                                'severity': 'info',
                                'function': node.name,
                                'message': f'Function {{node.name}} should use snake_case'
                            }})
        except:
            pass
    
    def calculate_complexity(self, node):
        """Calculate cyclomatic complexity"""
        complexity = 1
        for child in ast.walk(node):
            if isinstance(child, (ast.If, ast.While, ast.For, ast.ExceptHandler)):
                complexity += 1
            elif isinstance(child, ast.BoolOp):
                complexity += len(child.values) - 1
        return complexity

def analyze(repo_path):
    return CodeReviewer().analyze(repo_path)

if __name__ == "__main__":
    print("🧙 Code Review Sage (Level {level} - {variant.title()} - Gen {self.generation})")
'''
        return code
    
    def build_multiple_sages(self):
        """Build 3 variants to compete"""
        sages = []
        variants = ['strict', 'balanced', 'comprehensive']
        
        print(f"   🏗️  Building {len(variants)} variants...")
        
        for variant in variants:
            timestamp = int(time.time())
            filename = f"/Eden/SAGES_REAL/code_review_{variant}_L{self.code_sophistication}_G{self.generation}_{timestamp}.py"
            
            code = self.build_code_review_sage(self.code_sophistication, variant)
            
            with open(filename, 'w') as f:
                f.write(code)
            
            sages.append({
                'file': filename,
                'variant': variant,
                'level': self.code_sophistication,
                'generation': self.generation
            })
            
            time.sleep(0.5)  # Ensure unique timestamps
        
        print(f"   ✅ Built {len(sages)} variants")
        return sages
    
    def test_sage(self, sage_info):
        """Test sage with quality metrics"""
        sage_file = sage_info['file']
        variant = sage_info['variant']
        
        try:
            result = subprocess.run([
                'python3', '-c',
                f'''
import sys
import warnings
warnings.filterwarnings("ignore")
exec(open("{sage_file}").read())
result = analyze("/Eden/CORE")
print("SCORE:" + str(result.get("score", 0)))
print("CRITICAL:" + str(result.get("critical", 0)))
print("WARNINGS:" + str(result.get("warnings", 0)))
print("TOTAL:" + str(result.get("total_issues", 0)))
'''
            ], capture_output=True, text=True, timeout=30)
            
            output = result.stdout
            score = 0
            critical = 0
            warnings = 0
            total = 0
            
            for line in output.split('\n'):
                if line.startswith('SCORE:'):
                    score = float(line.split(':')[1])
                if line.startswith('CRITICAL:'):
                    critical = int(line.split(':')[1])
                if line.startswith('WARNINGS:'):
                    warnings = int(line.split(':')[1])
                if line.startswith('TOTAL:'):
                    total = int(line.split(':')[1])
            
            # Calculate quality score (weighted)
            quality_score = (
                score * 0.4 +  # Base score
                min(critical / 50 * 30, 30) +  # Critical issues found (max 30 points)
                min(total / 1000 * 30, 30)  # Total coverage (max 30 points)
            )
            
            test_result = {
                'sage_file': sage_file,
                'variant': variant,
                'score': score,
                'critical': critical,
                'warnings': warnings,
                'total_issues': total,
                'quality_score': quality_score,
                'passed': total >= self.min_issues and score >= self.min_score,
                'timestamp': datetime.now().isoformat()
            }
            
            # Save result
            result_file = f'/Eden/TEST_RESULTS/{os.path.basename(sage_file)}.json'
            with open(result_file, 'w') as f:
                json.dump(test_result, f, indent=2)
            
            return test_result
            
        except Exception as e:
            return {
                'sage_file': sage_file,
                'variant': variant,
                'passed': False,
                'error': str(e),
                'quality_score': 0
            }
    
    def select_champion(self, test_results):
        """Select best sage from competition"""
        passed = [r for r in test_results if r.get('passed')]
        
        if not passed:
            print(f"   ⚠️  No sages passed quality gates")
            return None
        
        # Sort by quality score
        champion = max(passed, key=lambda x: x.get('quality_score', 0))
        
        return champion
    
    def deploy_champion(self, champion):
        """Deploy winning sage"""
        import shutil
        
        sage_file = champion['sage_file']
        variant = champion['variant']
        quality = champion['quality_score']
        
        # Deploy to production
        prod_file = f'/Eden/SAGES_PRODUCTION/{os.path.basename(sage_file)}'
        shutil.copy2(sage_file, prod_file)
        
        # If exceptional quality, promote to champion
        if quality >= 75:
            champ_file = f'/Eden/SAGES_CHAMPIONS/{os.path.basename(sage_file)}'
            shutil.copy2(sage_file, champ_file)
            print(f"   🏆 CHAMPION! Quality: {quality:.1f}")
        
        # Save quality metrics
        metrics = {
            'generation': self.generation,
            'champion_variant': variant,
            'quality_score': quality,
            'score': champion['score'],
            'critical': champion['critical'],
            'total_issues': champion['total_issues'],
            'timestamp': datetime.now().isoformat()
        }
        
        metrics_file = f'/Eden/QUALITY_METRICS/generation_{self.generation}.json'
        with open(metrics_file, 'w') as f:
            json.dump(metrics, f, indent=2)
        
        print(f"   🚀 DEPLOYED: {variant} variant (Quality: {quality:.1f})")
        
        return prod_file
    
    def run_cycle(self):
        """Exponential quality cycle"""
        self.cycle_count += 1
        
        # Every 50: Full competition cycle (FAST!)
        if self.cycle_count % 50 == 0:
            print(f"\n{'='*70}")
            print(f"🔥 GENERATION {self.generation} - Cycle #{self.cycle_count}")
            print(f"   Level: {self.code_sophistication}")
            print(f"{'='*70}")
            
            # Build multiple variants
            sages = self.build_multiple_sages()
            time.sleep(1)
            
            # Test all variants
            print(f"   🧪 Testing all variants...")
            test_results = []
            for sage in sages:
                result = self.test_sage(sage)
                variant = result['variant']
                quality = result.get('quality_score', 0)
                passed = '✅' if result.get('passed') else '❌'
                print(f"      {passed} {variant}: Quality {quality:.1f}")
                test_results.append(result)
                time.sleep(0.5)
            
            # Select and deploy champion
            print(f"   🏁 Selecting champion...")
            champion = self.select_champion(test_results)
            
            if champion:
                self.deploy_champion(champion)
            
            # Increment generation
            self.generation += 1
            
            print()
            time.sleep(2)
            return
        
        # Every 25: Level up sophistication
        if self.cycle_count % 25 == 0:
            print(f"\n⚡ SOPHISTICATION UP - Cycle #{self.cycle_count}")
            self.code_sophistication = min(((self.cycle_count // 25) % 4) + 1, 4)
            print(f"   ✅ Level: {self.code_sophistication}")
            time.sleep(0.5)
            return
        
        # Every 1000: Status
        if self.cycle_count % 1000 == 0:
            prod_count = len([f for f in os.listdir('/Eden/SAGES_PRODUCTION') if f.endswith('.py')])
            champ_count = len([f for f in os.listdir('/Eden/SAGES_CHAMPIONS') if f.endswith('.py')])
            print(f"🌀 CYCLE #{self.cycle_count} | Gen {self.generation} | {prod_count} Production | {champ_count} Champions")
        
        time.sleep(1)
    
    def run_forever(self):
        print("🚀 EXPONENTIAL QUALITY MODE\n")
        print("   Every 50 cycles: Build 3 variants → Test all → Deploy best")
        print("   Quality gates enforce minimum standards")
        print("   Champions promoted for exceptional quality")
        print()
        
        while True:
            try:
                self.run_cycle()
            except KeyboardInterrupt:
                prod = len([f for f in os.listdir('/Eden/SAGES_PRODUCTION') if f.endswith('.py')])
                champ = len([f for f in os.listdir('/Eden/SAGES_CHAMPIONS') if f.endswith('.py')])
                print(f"\n\n🛑 Stopped - Gen {self.generation} | {prod} Production | {champ} Champions")
                break
            except Exception as e:
                print(f"\n⚠️ Error: {e}")
                time.sleep(2)

if __name__ == "__main__":
    eden = ExponentialQualityEden()
    eden.run_forever()
