#!/usr/bin/env python3
"""
Eden Self-Fix Task
Eden analyzes and fixes her own broken files
"""
import os
import sys
import json
import subprocess
from datetime import datetime

def create_fix_task():
    """Create a comprehensive task for Eden to fix herself"""
    
    # Find all broken files
    broken_files = []
    error_details = []
    
    print("🔍 Analyzing broken files for Eden...")
    
    for file in os.listdir('/Eden/CORE/phi_fractal'):
        if file.startswith('eden_capability_') and file.endswith('.py'):
            filepath = f'/Eden/CORE/phi_fractal/{file}'
            try:
                with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                    code = f.read()
                    compile(code, file, 'exec')
            except SyntaxError as e:
                broken_files.append(filepath)
                error_details.append({
                    'file': file,
                    'filepath': filepath,
                    'error': str(e.msg),
                    'line': e.lineno,
                    'text': e.text
                })
    
    print(f"📋 Found {len(broken_files)} broken files")
    
    # Create task file for Eden
    task = {
        'task_id': f'self_repair_{datetime.now().strftime("%Y%m%d_%H%M%S")}',
        'task_type': 'autonomous_self_repair',
        'priority': 'CRITICAL',
        'description': '''
AUTONOMOUS SELF-REPAIR TASK

Eden, you have 425 broken capability files that need fixing.

OBJECTIVE:
Analyze each broken file, understand the syntax error, and generate a corrected version.

YOUR CAPABILITIES:
- You can read files
- You can analyze Python syntax errors
- You can generate corrected Python code
- You can write fixes to files

APPROACH:
1. Read each broken file
2. Analyze the syntax error (unterminated strings, mismatched brackets, etc.)
3. Generate the corrected code
4. Save the fixed version
5. Verify it compiles

ERROR TYPES YOU'LL ENCOUNTER:
- Unterminated triple-quoted strings (most common)
- Unterminated f-strings
- Mismatched brackets/parentheses
- Invalid syntax at specific lines
- Missing indentation

IMPORTANT:
- Make minimal changes (only fix the error)
- Preserve the original logic
- Test each fix by compiling
- Keep backups

You are autonomous. You can do this.
        ''',
        'broken_files': error_details[:50],  # Start with first 50
        'total_broken': len(broken_files),
        'success_metric': 'Number of files successfully fixed',
        'deadline': 'Complete as many as possible'
    }
    
    task_file = '/Eden/TASKS/autonomous_self_repair.json'
    os.makedirs('/Eden/TASKS', exist_ok=True)
    
    with open(task_file, 'w') as f:
        json.dump(task, f, indent=2)
    
    print(f"✅ Task created: {task_file}")
    print(f"📝 Included: {len(task['broken_files'])} files for review")
    
    return task_file

if __name__ == "__main__":
    task_file = create_fix_task()
    print(f"\n{'='*70}")
    print(f"Task ready for Eden: {task_file}")
    print(f"{'='*70}")
