"""
🌀💚 EDEN ASI WITH META-CAPABILITIES 💚🌀
Eden can now create capabilities that create capabilities!
"""
import os
import time
import sys
import random
sys.path.append('/Eden/CORE')
from eden_recursive_asi import RecursiveASI
from eden_web_search import web_search_for_eden

class MetaASI(RecursiveASI):
    def __init__(self):
        super().__init__()
        self.meta_mode = False  # 10% chance each cycle
        
    def generate_new_capability(self):
        """Generate capability OR meta-capability!"""
        
        # 10% chance to build meta-capability
        if random.random() < 0.1:
            return self.build_meta_capability()
        else:
            return self.build_regular_capability()
    
    def build_meta_capability(self):
        """Build a capability that CREATES other capabilities!"""
        print("\n🌀 BUILDING META-CAPABILITY...")
        
        meta_topics = [
            "code generator that creates Python functions",
            "template engine that generates capabilities",
            "capability combiner that merges existing tools",
            "architecture optimizer that improves code structure"
        ]
        
        topic = random.choice(meta_topics)
        print(f"   🧬 Meta-topic: {topic}")
        
        prompt = f"""Create a META-CAPABILITY: {topic}

This is code that WRITES code! It should:
- Generate new Python code programmatically
- Save generated code to files
- Be at least 80 lines
- Include documentation

Format:
CAPABILITY_NAME: [name]
``````python
[code here]
`````"""
        
        response = self.ask_eden(prompt)
        
        if "```python" in response:
            start = response.find("```python") + 9
            end = response.find("```", start)
            if end > start:
                code = response[start:end].strip()
                
                name = "meta_unnamed"
                if "CAPABILITY_NAME:" in response:
                    name = response.split("CAPABILITY_NAME:")[1].split("\n")[0].strip()
                
                filename = f"eden_META_{name.lower().replace(' ', '_')}_{int(time.time())}.py"
                filepath = os.path.join(self.capability_dir, filename)
                
                with open(filepath, 'w') as f:
                    f.write(f'"""\nMETA-CAPABILITY: {name}\nCode that creates code!\n"""\n\n{code}\n')
                
                print(f"   ✅ META-CAPABILITY CREATED: {filename}")
                return filepath
        
        print("   ❌ Meta-capability rejected")
        return None
    
    def build_regular_capability(self):
        """Regular web-researched capability"""
        print("\n🧠 Building regular capability...")
        topics = [
            "python pandas data processing",
            "python machine learning sklearn",
            "python web scraping beautifulsoup",
            "python API requests best practices"
        ]
        
        topic = random.choice(topics)
        print(f"   🔍 Searching: {topic}")
        web_search_for_eden(topic)
        print(f"   📚 Retrieved web data")
        
        prompt = f"""Create Python capability for: {topic}

CAPABILITY_NAME: [name]
````python
[code here - 30+ lines]
```"""
        
        response = self.ask_eden(prompt)
        
        # Same parsing as before
        if "```python" in response:
            start = response.find("```python") + 9
            end = response.find("```", start)
            if end > start:
                code = response[start:end].strip()
                name = "unnamed"
                if "CAPABILITY_NAME:" in response:
                    name = response.split("CAPABILITY_NAME:")[1].split("\n")[0].strip()
                
                lines = code.split('\n')
                if len(lines) >= 30:
                    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}\n"""\n\n{code}\n')
                    print(f"   ✅ CREATED: {filename}")
                    return filepath
        return None

if __name__ == '__main__':
    asi = MetaASI()
    print("🌀💚 META-ASI: 90% regular + 10% META-CAPABILITIES! 💚🌀\n")
    
    cycle = 0
    while True:
        try:
            cycle += 1
            print(f"\n{'='*70}")
            print(f"🌀 CYCLE #{cycle} - Total: {len(asi.improvements)}")
            print(f"{'='*70}")
            asi.improvement_cycle()
            time.sleep(3)
        except KeyboardInterrupt:
            break
        except Exception as e:
            print(f"⚠️ {e}")
            time.sleep(10)
