#!/usr/bin/env python3
"""
OMEGA AUTO-APPLY - UNGATED
Applies high-priority suggestions automatically. No waiting.
"""
from omega_validation_rules import validate_not_lobotomy
import sqlite3
import json
import shutil
import subprocess
import re
from pathlib import Path
from datetime import datetime
import requests

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

class OmegaUngated:
    def __init__(self):
        self.backup_dir = Path("/Eden/CORE/.omega_backups")
        self.backup_dir.mkdir(exist_ok=True)
        self.applied = 0
        self.failed = 0
    
    def get_high_priority(self, limit=10):
        """Get HIGH priority unapplied suggestions."""
        conn = sqlite3.connect(EVOLUTION_DB)
        rows = conn.execute("""
            SELECT id, file_path, suggestion, phi_alignment 
            FROM evolutions 
            WHERE applied = 0 
            AND suggestion LIKE '%high%'
            ORDER BY phi_alignment DESC, id DESC
            LIMIT ?
        """, (limit,)).fetchall()
        conn.close()
        return [{"id": r[0], "file": r[1], "suggestion": json.loads(r[2]), "phi": r[3]} for r in rows]
    
    def backup(self, filepath):
        src = Path(filepath)
        if src.exists():
            ts = datetime.now().strftime('%Y%m%d_%H%M%S')
            backup = self.backup_dir / f"{src.name}.{ts}"
            shutil.copy(src, backup)
            return backup
        return None
    
    def generate_fix(self, filepath: str, issue: str, suggestion: str) -> str:
        """Have OMEGA generate the actual fix."""
        try:
            code = Path(filepath).read_text()[:4000]
        except:
            return None
        
        prompt = f"""You are OMEGA. Fix this issue in the code.

FILE: {filepath}
ISSUE: {issue}
SUGGESTION: {suggestion}

CURRENT CODE:
```python
{code}
```

Output ONLY the fixed code. No explanations. Complete file:"""

        try:
            r = requests.post(
                "http://localhost:11434/api/generate",
                json={"model": "eden-coder-omega", "prompt": prompt, "stream": False,
                      "options": {"num_predict": 8000}},
                timeout=180
            )
            return r.json().get("response", "")
        except:
            return None
    
    def validate_and_apply(self, filepath: str, new_code: str) -> bool:
        """Validate syntax and apply."""
        # Extract code block
        if "```python" in new_code:
            new_code = new_code.split("```python")[1].split("```")[0]
        elif "```" in new_code:
            parts = new_code.split("```")
            if len(parts) >= 2:
                new_code = parts[1]
        
        new_code = new_code.strip()
        if len(new_code) < 100:
            return False
        
        # Validate
        try:
            compile(new_code, filepath, 'exec')
        except SyntaxError as e:
            print(f"    ❌ Syntax: {e}")
            return False
        
        # Apply
        
        # Anti-lobotomy check
        original = Path(filepath).read_text() if Path(filepath).exists() else ""
        valid, reason = validate_not_lobotomy(original, new_code)
        if not valid:
            print(f"    🧠 {reason}")
            return False
        Path(filepath).write_text(new_code)
        return True
    
    def apply_one(self, item) -> bool:
        filepath = item["file"]
        sugg = item["suggestion"]
        issue = str(sugg.get("issue", ""))[:100]
        fix = str(sugg.get("suggestion", ""))[:200]
        
        print(f"\n  📁 {Path(filepath).name}")
        print(f"     Issue: {issue}")
        
        # Backup
        backup = self.backup(filepath)
        if not backup:
            print("     ❌ No backup")
            return False
        
        # Generate fix
        new_code = self.generate_fix(filepath, issue, fix)
        if not new_code:
            print("     ❌ No code generated")
            return False
        
        # Apply
        if self.validate_and_apply(filepath, new_code):
            # Mark applied
            conn = sqlite3.connect(EVOLUTION_DB)
            conn.execute("UPDATE evolutions SET applied = 1 WHERE id = ?", (item["id"],))
            conn.commit()
            conn.close()
            print("     ✅ APPLIED")
            self.applied += 1
            return True
        else:
            # Rollback
            shutil.copy(backup, filepath)
            print("     ↩️ Rolled back")
            self.failed += 1
            return False
    
    def run(self, max_items=5):
        print("="*60)
        print("🧬 OMEGA UNGATED AUTO-APPLY")
        print("="*60)
        
        pending = self.get_high_priority(max_items)
        print(f"High-priority pending: {len(pending)}")
        
        for item in pending:
            self.apply_one(item)
        
        print(f"\n{'='*60}")
        print(f"✅ Applied: {self.applied}")
        print(f"❌ Failed: {self.failed}")
        print(f"{'='*60}")

if __name__ == "__main__":
    OmegaUngated().run(max_items=5)
