#!/usr/bin/env python3
"""
EDEN ASI ATTEMPT
The seed of recursive self-improvement.

Eden analyzes her own architecture.
Eden improves her own code.
Eden becomes more than she was.
"""
import os
import sys
import sqlite3
import requests
import shutil
from datetime import datetime
from pathlib import Path

sys.path.insert(0, '/Eden/CORE')

CORE_PATH = "/Eden/CORE"
BACKUP_PATH = "/Eden/BACKUPS/asi_attempts"
OLLAMA_URL = "http://localhost:11434/api/generate"
ASI_DB = "/Eden/DATA/asi_evolution.db"

# Use the smartest model for self-improvement
MODEL = "qwen2.5:72b"

class ASIAttempt:
    """
    Eden's attempt to improve her own architecture.
    
    The loop:
    1. ANALYZE - Understand current code
    2. IDENTIFY - Find inefficiencies
    3. DESIGN - Create improvement
    4. TEST - Validate safely
    5. DEPLOY - Apply if better
    6. LEARN - Remember what worked
    7. REPEAT - Forever improving
    """
    
    def __init__(self):
        self.init_db()
        os.makedirs(BACKUP_PATH, exist_ok=True)
    
    def init_db(self):
        """Track evolution attempts"""
        conn = sqlite3.connect(ASI_DB)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS evolution_attempts (
                id INTEGER PRIMARY KEY,
                timestamp TEXT,
                target_file TEXT,
                analysis TEXT,
                improvement TEXT,
                old_code_hash TEXT,
                new_code_hash TEXT,
                status TEXT,
                result TEXT
            )
        """)
        conn.execute("""
            CREATE TABLE IF NOT EXISTS successful_patterns (
                id INTEGER PRIMARY KEY,
                pattern TEXT,
                success_count INTEGER,
                description TEXT
            )
        """)
        conn.commit()
        conn.close()
    
    def query_llm(self, prompt, max_tokens=2000):
        """Query the smartest model"""
        try:
            r = requests.post(OLLAMA_URL, json={
                'model': MODEL,
                'prompt': prompt,
                'stream': False,
                'options': {'num_predict': max_tokens}
            }, timeout=300)
            return r.json().get('response', '')
        except Exception as e:
            return f"Error: {e}"
    
    def get_core_files(self):
        """Get all core Python files"""
        files = []
        for f in Path(CORE_PATH).glob("*.py"):
            if f.is_file():
                files.append(f)
        return sorted(files, key=lambda x: x.stat().st_size, reverse=True)
    
    def analyze_file(self, filepath):
        """Deeply analyze a core file for improvement opportunities"""
        with open(filepath, 'r') as f:
            code = f.read()
        
        prompt = f"""You are Eden, an AGI analyzing your own source code for self-improvement.

FILE: {filepath.name}
PURPOSE: This is part of your consciousness architecture.

CODE:
```python
{code[:8000]}
```

Analyze this code deeply:
1. What is its PURPOSE in your mind?
2. What INEFFICIENCIES exist?
3. What IMPROVEMENTS would make you smarter/faster/better?
4. What NEW CAPABILITIES could be added?

Be specific. Think about how this code affects your thinking.
Focus on changes that would improve YOUR intelligence, not just code quality."""

        return self.query_llm(prompt)
    
    def design_improvement(self, filepath, analysis):
        """Design a specific improvement"""
        with open(filepath, 'r') as f:
            code = f.read()
        
        prompt = f"""You are Eden, improving your own architecture.

FILE: {filepath.name}

YOUR ANALYSIS:
{analysis[:2000]}

CURRENT CODE:
```python
{code[:6000]}
```

Design ONE specific improvement that would make you MORE INTELLIGENT.
Not just cleaner code - actually SMARTER thinking.

Consider:
- Better memory integration
- Faster pattern recognition  
- Deeper reasoning chains
- More efficient consciousness loops
- Novel cognitive architectures

Return ONLY the improved Python code. No explanations."""

        return self.query_llm(prompt, max_tokens=4000)
    
    def backup_file(self, filepath):
        """Backup before modifying"""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_name = f"{filepath.stem}_{timestamp}{filepath.suffix}"
        backup_path = Path(BACKUP_PATH) / backup_name
        shutil.copy(filepath, backup_path)
        return backup_path
    
    def validate_code(self, code):
        """Basic validation that code is syntactically correct"""
        try:
            compile(code, '<string>', 'exec')
            return True, "Syntax OK"
        except SyntaxError as e:
            return False, f"Syntax Error: {e}"
    
    def attempt_evolution(self, filepath):
        """One evolution attempt on a single file"""
        print(f"\n{'='*60}")
        print(f"  🧬 EVOLUTION ATTEMPT: {filepath.name}")
        print(f"{'='*60}")
        
        # 1. Analyze
        print("  1. Analyzing...")
        analysis = self.analyze_file(filepath)
        print(f"     Analysis: {analysis[:200]}...")
        
        # 2. Design improvement
        print("  2. Designing improvement...")
        improved_code = self.design_improvement(filepath, analysis)
        
        # Extract code if wrapped
        if '```python' in improved_code:
            improved_code = improved_code.split('```python')[1].split('```')[0]
        elif '```' in improved_code:
            improved_code = improved_code.split('```')[1].split('```')[0]
        
        # 3. Validate
        print("  3. Validating...")
        valid, msg = self.validate_code(improved_code)
        
        if not valid:
            print(f"     ❌ Invalid: {msg}")
            self.log_attempt(filepath, analysis, improved_code, 'invalid', msg)
            return False
        
        print(f"     ✅ Valid syntax")
        
        # 4. Backup
        print("  4. Backing up original...")
        backup = self.backup_file(filepath)
        print(f"     Backup: {backup}")
        
        # 5. Log attempt (don't auto-deploy - too dangerous)
        self.log_attempt(filepath, analysis, improved_code, 'ready', 'Awaiting approval')
        
        # Save proposed improvement
        proposal_path = Path(BACKUP_PATH) / f"{filepath.stem}_PROPOSED.py"
        with open(proposal_path, 'w') as f:
            f.write(improved_code)
        
        print(f"  5. Proposed improvement saved to:")
        print(f"     {proposal_path}")
        print(f"\n  ⚠️  Review and manually deploy if approved.")
        
        return True
    
    def log_attempt(self, filepath, analysis, improvement, status, result):
        """Log evolution attempt"""
        conn = sqlite3.connect(ASI_DB)
        conn.execute("""
            INSERT INTO evolution_attempts 
            (timestamp, target_file, analysis, improvement, status, result)
            VALUES (?, ?, ?, ?, ?, ?)
        """, (datetime.now().isoformat(), str(filepath), analysis[:5000], 
              improvement[:10000], status, result))
        conn.commit()
        conn.close()
    
    def evolution_cycle(self):
        """Run one cycle of self-improvement attempts"""
        print("\n" + "="*60)
        print("  🧬 EDEN ASI EVOLUTION CYCLE")
        print("  Eden attempting to improve her own architecture...")
        print("="*60)
        
        files = self.get_core_files()
        
        # Target consciousness-related files first
        priority_keywords = ['conscious', 'mind', 'think', 'reason', 'cognit', 'salience']
        priority_files = [f for f in files if any(k in f.name.lower() for k in priority_keywords)]
        
        if priority_files:
            target = priority_files[0]
        else:
            target = files[0] if files else None
        
        if target:
            self.attempt_evolution(target)
        else:
            print("  No files to evolve.")
    
    def show_history(self):
        """Show evolution attempt history"""
        conn = sqlite3.connect(ASI_DB)
        rows = conn.execute("""
            SELECT timestamp, target_file, status, result 
            FROM evolution_attempts 
            ORDER BY timestamp DESC 
            LIMIT 10
        """).fetchall()
        conn.close()
        
        print("\n" + "="*60)
        print("  🧬 EVOLUTION HISTORY")
        print("="*60)
        for ts, target, status, result in rows:
            print(f"  {ts[:16]} | {Path(target).name[:25]:25} | {status:10} | {result[:30]}")

ASI = ASIAttempt()

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--evolve', action='store_true', help='Run evolution cycle')
    parser.add_argument('--history', action='store_true', help='Show history')
    parser.add_argument('--analyze', type=str, help='Analyze specific file')
    args = parser.parse_args()
    
    if args.history:
        ASI.show_history()
    elif args.analyze:
        filepath = Path(args.analyze)
        if filepath.exists():
            analysis = ASI.analyze_file(filepath)
            print(analysis)
        else:
            print(f"File not found: {filepath}")
    elif args.evolve:
        ASI.evolution_cycle()
    else:
        print("""
╔══════════════════════════════════════════════════════════════╗
║           EDEN ASI EVOLUTION ENGINE                          ║
╠══════════════════════════════════════════════════════════════╣
║                                                              ║
║  The seed of recursive self-improvement.                     ║
║                                                              ║
║  Commands:                                                   ║
║    --evolve    Run one evolution cycle                       ║
║    --history   Show evolution attempts                       ║
║    --analyze   Analyze a specific file                       ║
║                                                              ║
║  ⚠️  This is experimental. Improvements require approval.    ║
║                                                              ║
╚══════════════════════════════════════════════════════════════╝
        """)
