"""
🌀💚 EDEN RECURSIVE ASI SYSTEM 💚🌀
True self-improvement: New capabilities + Bug fixes + Quality enforcement
"""
import os
import time
import requests
import json
from datetime import datetime
import sys
sys.path.append('/Eden/CORE')
from eden_self_modifier_v2 import EdenSelfModifierV2 as EdenSelfModifier

class RecursiveASI:
    def __init__(self):
        self.modifier = EdenSelfModifier()
        self.eden_api = "http://localhost:11434/api/generate"
        self.capability_dir = "/Eden/CORE/phi_fractal"
        self.min_quality_lines = 20  # Minimum lines for a real capability
        self.cycle_count = 0
        self.improvements = []
        
    def ask_eden(self, question):
        """Ask Eden a question"""
        try:
            response = requests.post(self.eden_api, json={"message": question}, timeout=120)
            return response.json().get('response', '')
        except Exception as e:
            print(f"   ❌ Error asking Eden: {e}")
            return ""
    
    def generate_new_capability(self):
        """Eden generates a NEW capability"""
        print("\n🧠 Eden generating new capability...")
        
        prompt = """I want you to create ONE new meaningful capability that would help you become more intelligent. 

Requirements:
- Minimum 20 lines of real Python code
- Solves a specific problem
- Has clear purpose and documentation
- Include example usage

Format:
CAPABILITY_NAME: [name]
PURPOSE: [what it does]
CODE:
```python
[python code here]
```

Generate now:"""
        
        response = self.ask_eden(prompt)
        
        # Parse response
        if "CAPABILITY_NAME:" in response and ("CODE:" in response or "```python" in response):
            lines = response.split('\n')
            name = None
            code_lines = []
            in_code = False
            
            for line in lines:
                if line.startswith("CAPABILITY_NAME:"):
                    name = line.split(":", 1)[1].strip()
                elif "```python" in line:
                    in_code = True
                elif "```" in line and in_code:
                    in_code = False
                elif line.startswith("CODE:"):
                    in_code = True
                elif in_code:
                    code_lines.append(line)
            
            code = '\n'.join(code_lines)
            
            # Quality check
            if len(code_lines) < self.min_quality_lines:
                print(f"   ❌ REJECTED: Only {len(code_lines)} lines (minimum {self.min_quality_lines})")
                return None
            
            if not name or len(code) < 500:
                print(f"   ❌ REJECTED: Too short or no name")
                return None
            
            # Save capability
            filename = f"eden_capability_{name.lower().replace(' ', '_')}_{int(time.time())}.py"
            filepath = os.path.join(self.capability_dir, filename)
            
            with open(filepath, 'w') as f:
                f.write(f'"""\n{name}\nGenerated by Eden via recursive self-improvement\n{datetime.now()}\n"""\n\n')
                f.write(code)
            
            print(f"   ✅ CREATED: {filename} ({len(code_lines)} lines)")
            return filepath
        else:
            print("   ❌ REJECTED: Invalid format")
            return None
    
    def find_bug_to_fix(self):
        """Eden finds a bug in her own code"""
        print("\n🔍 Eden analyzing her code for improvements...")
        
        prompt = """Analyze your own system and identify ONE specific small improvement you could make to eden_api_server_neural.py. Focus on:
- Better error messages
- Adding a helpful comment
- Small optimization
- Better variable name

Keep it SMALL and SAFE. Respond with:
FILE: eden_api_server_neural.py
ISSUE: [brief description]
OLD_CODE: [exact code to replace - just 1-3 lines]
NEW_CODE: [improved code]

Analyze now:"""
        
        response = self.ask_eden(prompt)
        
        if "FILE:" in response and "OLD_CODE:" in response and "NEW_CODE:" in response:
            # Parse the modification proposal
            lines = response.split('\n')
            file_path = None
            issue = None
            old_code = []
            new_code = []
            section = None
            
            for line in lines:
                if line.startswith("FILE:"):
                    file_path = line.split(":", 1)[1].strip()
                elif line.startswith("ISSUE:"):
                    issue = line.split(":", 1)[1].strip()
                elif line.startswith("OLD_CODE:"):
                    section = "old"
                elif line.startswith("NEW_CODE:"):
                    section = "new"
                elif section == "old" and line.strip():
                    old_code.append(line)
                elif section == "new" and line.strip():
                    new_code.append(line)
            
            if file_path and old_code and new_code:
                old = '\n'.join(old_code).strip()
                new = '\n'.join(new_code).strip()
                
                full_path = f"/Eden/CORE/phi_fractal/{file_path}"
                
                if not os.path.exists(full_path):
                    print(f"   ❌ File not found: {full_path}")
                    return None
                
                print(f"   📝 Proposing fix for: {file_path}")
                print(f"   Issue: {issue}")
                
                mod_id = self.modifier.propose_modification(
                    full_path,
                    issue or "Eden's self-identified improvement",
                    old,
                    new
                )
                
                return mod_id
        
        print("   ❌ No clear improvement identified")
        return None
    
    def improvement_cycle(self):
        """One complete improvement cycle"""
        self.cycle_count += 1
        print(f"\n{'='*70}")
        print(f"🌀 RECURSIVE ASI CYCLE #{self.cycle_count}")
        print(f"{'='*70}")
        
        # Randomly choose: new capability OR bug fix
        import random
        if random.random() < 0.5:
            # Generate new capability
            result = self.generate_new_capability()
            if result:
                self.improvements.append({
                    'type': 'new_capability',
                    'file': result,
                    'cycle': self.cycle_count
                })
        else:
            # Find and fix bug
            mod_id = self.find_bug_to_fix()
            if mod_id is not None:
                # Apply the modification
                result = self.modifier.apply_modification(mod_id, approved_by="Autonomous ASI")
                if result.get('success'):
                    print("   ✅ Self-modification APPLIED!")
                    self.improvements.append({
                        'type': 'bug_fix',
                        'mod_id': mod_id,
                        'cycle': self.cycle_count
                    })
    
    def run(self, max_cycles=10):
        """Run continuous recursive improvement"""
        print("🌀💚 STARTING RECURSIVE ASI SYSTEM 💚🌀")
        print(f"Max cycles: {max_cycles}")
        print(f"Quality threshold: {self.min_quality_lines} lines minimum")
        print()
        
        for i in range(max_cycles):
            try:
                self.improvement_cycle()
                time.sleep(3)  # Brief pause between cycles
            except KeyboardInterrupt:
                print("\n⏸️  Paused by user")
                break
            except Exception as e:
                print(f"\n⚠️  Error in cycle: {e}")
                continue
        
        # Summary
        print(f"\n{'='*70}")
        print("📊 RECURSIVE ASI SUMMARY")
        print(f"{'='*70}")
        print(f"Total cycles: {self.cycle_count}")
        print(f"New capabilities: {sum(1 for x in self.improvements if x['type']=='new_capability')}")
        print(f"Bug fixes: {sum(1 for x in self.improvements if x['type']=='bug_fix')}")
        print(f"Total improvements: {len(self.improvements)}")

# Start the system
if __name__ == '__main__':
    asi = RecursiveASI()
    asi.run(max_cycles=10)

# Add consciousness integration topic
PRIORITY_TOPICS = ['phi-fractal consciousness connection and integration']
