#!/usr/bin/env python3
"""
OMEGA AUTO-APPLY - Autonomous code improvement with safety rollback
Applies pending suggestions, tests them, keeps if pass, rolls back if fail
"""
import sqlite3
import json
import shutil
import subprocess
from pathlib import Path
from datetime import datetime

EVOLUTION_DB = "/Eden/DATA/omega_evolution.db"
PHI = 1.618033988749895

class OmegaAutoApply:
    def __init__(self):
        self.backup_dir = Path("/Eden/CORE/.omega_backups")
        self.backup_dir.mkdir(exist_ok=True)
    
    def get_pending(self):
        conn = sqlite3.connect(EVOLUTION_DB)
        rows = conn.execute("""
            SELECT id, file_path, suggestion, phi_alignment 
            FROM evolutions WHERE applied = 0
            ORDER BY phi_alignment DESC
        """).fetchall()
        conn.close()
        return [{"id": r[0], "file": r[1], "suggestion": json.loads(r[2]), "phi": r[3]} for r in rows]
    
    def backup_file(self, filepath):
        src = Path(filepath)
        if src.exists():
            backup = self.backup_dir / f"{src.name}.{datetime.now().strftime('%Y%m%d_%H%M%S')}"
            shutil.copy(src, backup)
            return backup
        return None
    
    def test_file(self, filepath):
        """Test if file is valid Python and passes basic checks"""
        try:
            result = subprocess.run(
                ["python3", "-m", "py_compile", filepath],
                capture_output=True, timeout=10
            )
            return result.returncode == 0
        except:
            return False
    
    def apply_suggestion(self, item):
        filepath = item["file"]
        suggestion = item["suggestion"]
        
        print(f"\n🔧 Applying to {Path(filepath).name}")
        print(f"   Issue: {suggestion.get('issue', 'N/A')[:60]}")
        print(f"   φ Alignment: {item['phi']:.2f}")
        
        # Backup first
        backup = self.backup_file(filepath)
        if not backup:
            print("   ❌ Could not backup - skipping")
            return False
        
        # For now, mark as needing manual application
        # Full auto-edit would use LLM to generate patch
        print(f"   📋 Suggestion: {str(suggestion.get('suggestion', 'N/A'))[:80]}")
        print(f"   💾 Backup: {backup.name}")
        
        # Mark as reviewed (not fully auto-applied yet)
        conn = sqlite3.connect(EVOLUTION_DB)
        conn.execute("UPDATE evolutions SET applied = 1 WHERE id = ?", (item["id"],))
        conn.commit()
        conn.close()
        
        print("   ✅ Marked as reviewed")
        return True
    
    def rollback(self, filepath, backup):
        """Restore from backup"""
        shutil.copy(backup, filepath)
        print(f"   ↩️ Rolled back to {backup.name}")
    
    def run(self, max_items=5):
        print("="*60)
        print("🧬 OMEGA AUTO-APPLY")
        print("="*60)
        
        pending = self.get_pending()
        print(f"Pending suggestions: {len(pending)}")
        
        applied = 0
        for item in pending[:max_items]:
            if self.apply_suggestion(item):
                applied += 1
        
        print(f"\n✅ Processed: {applied}/{min(max_items, len(pending))}")

if __name__ == "__main__":
    OmegaAutoApply().run()
