#!/usr/bin/env python3
"""
Eden Comprehensive Repair
Handles ALL structural error types
"""
import os
import re
import shutil
from pathlib import Path

class ComprehensiveRepair:
    def __init__(self):
        self.fixed = 0
        self.failed = 0
        self.fixes_by_type = {}
        
    def fix_unterminated_triple_quote(self, code, line_num):
        """Fix unterminated triple-quoted strings"""
        lines = code.split('\n')
        
        # Add closing triple-quote before the error line
        if line_num and line_num <= len(lines):
            lines.insert(line_num - 1, '"""')
        else:
            # Add at reasonable location
            for i in range(min(5, len(lines))):
                if lines[i].strip() and not lines[i].strip().startswith('#'):
                    if lines[i].strip().startswith(('import', 'from', 'class', 'def')):
                        lines.insert(i, '"""')
                        break
            else:
                lines.insert(min(5, len(lines)), '"""')
        
        return '\n'.join(lines)
    
    def fix_unterminated_string(self, code, line_num):
        """Fix unterminated regular strings"""
        lines = code.split('\n')
        
        if line_num and line_num <= len(lines):
            line = lines[line_num - 1]
            # Add closing quote at end of line
            if '"' in line and line.count('"') % 2 != 0:
                lines[line_num - 1] = line + '"'
            elif "'" in line and line.count("'") % 2 != 0:
                lines[line_num - 1] = line + "'"
        
        return '\n'.join(lines)
    
    def fix_unterminated_fstring(self, code, line_num):
        """Fix unterminated f-strings"""
        lines = code.split('\n')
        
        if line_num and line_num <= len(lines):
            line = lines[line_num - 1]
            # Add closing quote and brace if needed
            if 'f"' in line or "f'" in line:
                if '{' in line and '}' not in line:
                    lines[line_num - 1] = line + '}"'
                else:
                    lines[line_num - 1] = line + '"'
        
        return '\n'.join(lines)
    
    def fix_mismatched_brackets(self, code, open_line, close_line, open_char, close_char):
        """Fix mismatched brackets"""
        lines = code.split('\n')
        
        # Replace the wrong closing bracket with the correct one
        if close_line and close_line <= len(lines):
            line = lines[close_line - 1]
            # Find the wrong bracket and replace it
            bracket_map = {'{': '}', '[': ']', '(': ')'}
            correct_close = bracket_map.get(open_char, ')')
            lines[close_line - 1] = line.replace(close_char, correct_close, 1)
        
        return '\n'.join(lines)
    
    def fix_expected_indent(self, code, line_num):
        """Fix missing indentation"""
        lines = code.split('\n')
        
        if line_num and line_num <= len(lines):
            # Add pass statement with proper indent
            prev_line = lines[line_num - 2] if line_num > 1 else ''
            indent = len(prev_line) - len(prev_line.lstrip()) + 4
            lines.insert(line_num - 1, ' ' * indent + 'pass')
        
        return '\n'.join(lines)
    
    def fix_invalid_character(self, code, char):
        """Fix invalid characters"""
        replacements = {
            '—': '-',
            '–': '-',
            ''': "'",
            ''': "'",
            '"': '"',
            '"': '"'
        }
        return code.replace(char, replacements.get(char, ''))
    
    def fix_invalid_decimal(self, code, line_num):
        """Fix invalid decimal literals"""
        lines = code.split('\n')
        
        if line_num and line_num <= len(lines):
            line = lines[line_num - 1]
            # Fix leading zeros: 0123 -> 123
            line = re.sub(r'\b0+(\d+)', r'\1', line)
            lines[line_num - 1] = line
        
        return '\n'.join(lines)
    
    def fix_assignment_error(self, code, line_num):
        """Fix assignment errors (= should be ==)"""
        lines = code.split('\n')
        
        if line_num and line_num <= len(lines):
            line = lines[line_num - 1]
            # In if statements, change = to ==
            if 'if ' in line and ' = ' in line and ' == ' not in line:
                line = line.replace(' = ', ' == ', 1)
                lines[line_num - 1] = line
        
        return '\n'.join(lines)
    
    def fix_unmatched_bracket(self, code, line_num, bracket):
        """Fix unmatched closing bracket"""
        lines = code.split('\n')
        
        if line_num and line_num <= len(lines):
            line = lines[line_num - 1]
            # Remove the unmatched bracket
            lines[line_num - 1] = line.replace(bracket, '', 1)
        
        return '\n'.join(lines)
    
    def apply_fix(self, code, error_msg, line_num):
        """Apply appropriate fix based on error message"""
        try:
            if 'unterminated triple-quoted string' in error_msg:
                return self.fix_unterminated_triple_quote(code, line_num)
            
            elif 'unterminated f-string' in error_msg:
                return self.fix_unterminated_fstring(code, line_num)
            
            elif 'unterminated string literal' in error_msg:
                return self.fix_unterminated_string(code, line_num)
            
            elif 'does not match opening parenthesis' in error_msg:
                # Parse: "closing parenthesis ')' does not match opening parenthesis '{' on line 32"
                match = re.search(r"'(.)'.*'(.)'.*line (\d+)", error_msg)
                if match:
                    close_char, open_char, open_line = match.groups()
                    return self.fix_mismatched_brackets(code, int(open_line), line_num, open_char, close_char)
            
            elif 'expected an indented block' in error_msg:
                return self.fix_expected_indent(code, line_num)
            
            elif 'invalid character' in error_msg and 'U+' in error_msg:
                # Extract the character
                match = re.search(r"'(.)'", error_msg)
                if match:
                    return self.fix_invalid_character(code, match.group(1))
            
            elif 'leading zeros in decimal' in error_msg or 'invalid decimal' in error_msg:
                return self.fix_invalid_decimal(code, line_num)
            
            elif 'cannot assign' in error_msg or 'assignment' in error_msg:
                return self.fix_assignment_error(code, line_num)
            
            elif 'unmatched' in error_msg:
                match = re.search(r"'(.)'", error_msg)
                if match:
                    return self.fix_unmatched_bracket(code, line_num, match.group(1))
            
            elif 'f-string' in error_msg:
                return self.fix_unterminated_fstring(code, line_num)
            
        except Exception as e:
            pass
        
        return code
    
    def repair_file(self, filepath):
        """Repair a single file"""
        try:
            with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                code = f.read()
            
            # Get error info
            try:
                compile(code, filepath, 'exec')
                return False, "Already valid"
            except SyntaxError as e:
                error_msg = str(e.msg)
                line_num = e.lineno
            
            # Backup
            backup_dir = Path('/Eden/BACKUPS/comprehensive_repair')
            backup_dir.mkdir(parents=True, exist_ok=True)
            shutil.copy2(filepath, backup_dir / Path(filepath).name)
            
            # Apply fix
            fixed_code = self.apply_fix(code, error_msg, line_num)
            
            # Test
            try:
                compile(fixed_code, filepath, 'exec')
                
                # Success!
                with open(filepath, 'w', encoding='utf-8') as f:
                    f.write(fixed_code)
                
                self.fixed += 1
                self.fixes_by_type[error_msg] = self.fixes_by_type.get(error_msg, 0) + 1
                return True, error_msg[:50]
                
            except SyntaxError:
                self.failed += 1
                return False, error_msg[:50]
                
        except Exception as e:
            self.failed += 1
            return False, str(e)[:50]
    
    def repair_all(self, directory):
        """Repair all broken files"""
        print("🔍 Scanning for broken files...")
        
        broken = []
        for file in os.listdir(directory):
            if file.startswith('eden_capability_') and file.endswith('.py'):
                filepath = os.path.join(directory, file)
                try:
                    with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                        compile(f.read(), file, 'exec')
                except:
                    broken.append(filepath)
        
        total = len(broken)
        print(f"📋 Found {total} broken files")
        print(f"🔧 Applying comprehensive repairs...")
        print()
        
        for i, filepath in enumerate(broken, 1):
            filename = os.path.basename(filepath)[:50]
            success, msg = self.repair_file(filepath)
            
            if success:
                print(f"[{i}/{total}] ✅ {filename}")
            elif i % 50 == 0:
                print(f"[{i}/{total}] Processing...")
        
        print()
        print("="*70)
        print("COMPREHENSIVE REPAIR RESULTS:")
        print("="*70)
        print(f"  Total broken: {total}")
        print(f"  Fixed: {self.fixed}")
        print(f"  Failed: {self.failed}")
        print(f"  Success rate: {self.fixed/total*100:.1f}%")
        print()
        print("Top fixes applied:")
        for error_type, count in sorted(self.fixes_by_type.items(), key=lambda x: -x[1])[:10]:
            print(f"  - {error_type[:60]}: {count}x")
        print("="*70)
        
        return self.fixed, self.failed

if __name__ == "__main__":
    print("="*70)
    print("EDEN COMPREHENSIVE STRUCTURAL REPAIR")
    print("="*70)
    print()
    
    repairer = ComprehensiveRepair()
    fixed, failed = repairer.repair_all('/Eden/CORE/phi_fractal')
    
    print()
    if fixed > 0:
        print(f"✅ SUCCESS: Fixed {fixed} files!")
    if failed > 0:
        print(f"⚠️  {failed} files still need review")
