#!/usr/bin/env python3
"""
Automatically fix common issues in Eden's capabilities and test them
"""
import os
import re
import sys
from pathlib import Path

def fix_imports(filepath):
    """Fix missing typing imports and other common issues"""
    with open(filepath, 'r') as f:
        content = f.read()
    
    original = content
    
    # Check if typing imports are needed
    needs_typing = bool(re.search(r'\b(List|Dict|Tuple|Optional|Callable|Any)\b', content))
    has_typing_import = 'from typing import' in content or 'import typing' in content
    
    if needs_typing and not has_typing_import:
        # Find what's needed
        typing_needs = set()
        if re.search(r'\bList\b', content): typing_needs.add('List')
        if re.search(r'\bDict\b', content): typing_needs.add('Dict')
        if re.search(r'\bTuple\b', content): typing_needs.add('Tuple')
        if re.search(r'\bOptional\b', content): typing_needs.add('Optional')
        if re.search(r'\bCallable\b', content): typing_needs.add('Callable')
        if re.search(r'\bAny\b', content): typing_needs.add('Any')
        
        # Add import after the docstring
        typing_import = f"from typing import {', '.join(sorted(typing_needs))}\n"
        
        # Find end of docstring
        lines = content.split('\n')
        insert_pos = 0
        in_docstring = False
        for i, line in enumerate(lines):
            if '"""' in line:
                if not in_docstring:
                    in_docstring = True
                else:
                    insert_pos = i + 1
                    break
        
        if insert_pos > 0:
            lines.insert(insert_pos, typing_import)
            content = '\n'.join(lines)
    
    # Save if changed
    if content != original:
        with open(filepath, 'w') as f:
            f.write(content)
        return True
    return False

def test_capability(filepath):
    """Try to import and validate the capability"""
    try:
        # Extract module name
        module_name = Path(filepath).stem
        
        # Try to compile it first
        with open(filepath, 'r') as f:
            code = f.read()
        compile(code, filepath, 'exec')
        
        return True, "Syntax OK"
    except SyntaxError as e:
        return False, f"Syntax Error: {e}"
    except Exception as e:
        return False, f"Error: {e}"

def main():
    cap_dir = Path("/Eden/CAPABILITIES")
    meta_files = list(cap_dir.glob("eden_meta_*.py"))
    
    print(f"Found {len(meta_files)} meta-validated capabilities")
    print()
    
    fixed_count = 0
    success_count = 0
    error_count = 0
    errors = []
    
    for i, filepath in enumerate(meta_files):
        # Fix imports
        was_fixed = fix_imports(filepath)
        if was_fixed:
            fixed_count += 1
        
        # Test
        success, msg = test_capability(filepath)
        if success:
            success_count += 1
        else:
            error_count += 1
            if len(errors) < 10:  # Keep first 10 errors
                errors.append((filepath.name, msg))
        
        # Progress
        if (i + 1) % 100 == 0:
            print(f"  Processed {i+1}/{len(meta_files)}...")
    
    print()
    print("="*70)
    print("RESULTS:")
    print("="*70)
    print(f"Total Capabilities:     {len(meta_files)}")
    print(f"Import Fixes Applied:   {fixed_count}")
    print(f"✅ Valid & Working:     {success_count} ({success_count*100//len(meta_files)}%)")
    print(f"❌ Errors:              {error_count} ({error_count*100//len(meta_files)}%)")
    
    if errors:
        print()
        print("Sample Errors:")
        for name, msg in errors[:5]:
            print(f"  {name}: {msg[:80]}")

if __name__ == '__main__':
    main()
