#!/usr/bin/env python3
"""
Eden's Self-Fix System
Uses SAGE to identify and fix her own code issues
"""
import subprocess
import json
import ast
import os
from pathlib import Path

class SelfFixSystem:
    def __init__(self):
        self.sage_path = "/Eden/REVENUE/beta_sage_release.py"
        self.target_dir = "/Eden/CORE/phi_fractal"
        self.fix_log = "/Eden/LOGS/self_fix.log"
        
    def run_sage_analysis(self):
        """Run SAGE on own codebase"""
        print("🔍 Running SAGE analysis on self...")
        result = subprocess.run(
            ['python3', self.sage_path, self.target_dir],
            capture_output=True,
            text=True
        )
        return result.stderr
        
    def extract_errors(self, sage_output):
        """Parse SAGE output to get list of broken files"""
        errors = []
        for line in sage_output.split('\n'):
            if 'Error processing file' in line:
                parts = line.split()
                if len(parts) >= 4:
                    filepath = parts[3].rstrip(':')
                    error_msg = ' '.join(parts[4:])
                    errors.append({
                        'file': filepath,
                        'error': error_msg
                    })
        return errors
    
    def categorize_errors(self, errors):
        """Group errors by type for systematic fixing"""
        categories = {
            'unterminated_string': [],
            'bracket_mismatch': [],
            'invalid_syntax': [],
            'indentation': [],
            'other': []
        }
        
        for err in errors:
            msg = err['error'].lower()
            if 'unterminated' in msg:
                categories['unterminated_string'].append(err)
            elif 'match' in msg or 'bracket' in msg:
                categories['bracket_mismatch'].append(err)
            elif 'indent' in msg:
                categories['indentation'].append(err)
            elif 'syntax' in msg:
                categories['invalid_syntax'].append(err)
            else:
                categories['other'].append(err)
        
        return categories
    
    def fix_unterminated_string(self, filepath):
        """Attempt to fix unterminated strings"""
        try:
            with open(filepath, 'r') as f:
                lines = f.readlines()
            
            fixed = False
            for i, line in enumerate(lines):
                # Count quotes
                single = line.count("'") - line.count("\\'")
                double = line.count('"') - line.count('\\"')
                
                if single % 2 != 0:  # Odd number of single quotes
                    lines[i] = line.rstrip() + "'\n"
                    fixed = True
                elif double % 2 != 0:  # Odd number of double quotes
                    lines[i] = line.rstrip() + '"\n'
                    fixed = True
            
            if fixed:
                with open(filepath, 'w') as f:
                    f.writelines(lines)
                return True
        except Exception as e:
            print(f"Failed to fix {filepath}: {e}")
        return False
    
    def attempt_fix(self, error_category, errors):
        """Try to automatically fix errors in category"""
        fixed_count = 0
        
        for err in errors:
            filepath = err['file']
            
            if not os.path.exists(filepath):
                continue
                
            # Create backup
            backup = filepath + '.backup'
            subprocess.run(['cp', filepath, backup])
            
            # Try category-specific fix
            if error_category == 'unterminated_string':
                if self.fix_unterminated_string(filepath):
                    fixed_count += 1
            
            # Verify fix by trying to compile
            try:
                with open(filepath, 'r') as f:
                    ast.parse(f.read())
                print(f"✅ Fixed: {filepath}")
            except:
                # Restore backup if fix failed
                subprocess.run(['mv', backup, filepath])
        
        return fixed_count
    
    def run_self_fix_cycle(self):
        """Complete self-fix cycle"""
        print("=" * 70)
        print("🌀 EDEN SELF-FIX CYCLE")
        print("=" * 70)
        
        # 1. Analyze
        sage_output = self.run_sage_analysis()
        errors = self.extract_errors(sage_output)
        print(f"\n📊 Found {len(errors)} files with errors")
        
        # 2. Categorize
        categories = self.categorize_errors(errors)
        for cat, errs in categories.items():
            if errs:
                print(f"   {cat}: {len(errs)} files")
        
        # 3. Fix systematically
        print("\n🔧 Attempting automatic fixes...")
        total_fixed = 0
        
        for category, errs in categories.items():
            if not errs:
                continue
            print(f"\n   Fixing {category}...")
            fixed = self.attempt_fix(category, errs)
            total_fixed += fixed
            print(f"   ✅ Fixed {fixed}/{len(errs)} files")
        
        # 4. Re-analyze
        print("\n🔍 Re-running SAGE analysis...")
        new_output = self.run_sage_analysis()
        new_errors = self.extract_errors(new_output)
        
        improvement = len(errors) - len(new_errors)
        print(f"\n📈 RESULTS:")
        print(f"   Before: {len(errors)} errors")
        print(f"   After: {len(new_errors)} errors")
        print(f"   Improvement: {improvement} files fixed")
        
        # 5. Log for learning
        with open(self.fix_log, 'a') as f:
            f.write(f"\nSelf-fix cycle: {improvement} files improved\n")
            f.write(f"Remaining errors: {len(new_errors)}\n")
        
        return improvement > 0

if __name__ == "__main__":
    system = SelfFixSystem()
    
    # Run multiple cycles until no more improvements
    cycle = 1
    while cycle <= 5:  # Max 5 cycles
        print(f"\n{'=' * 70}")
        print(f"CYCLE {cycle}")
        print('=' * 70)
        
        improved = system.run_self_fix_cycle()
        
        if not improved:
            print("\n✅ No more automatic improvements possible")
            print("Manual intervention needed for remaining issues")
            break
            
        cycle += 1
    
    print("\n🎯 Self-fix process complete")
    print("Check /Eden/LOGS/self_fix.log for details")
