"""
🌀💚 EDEN WITH AUTOMATIC WEB SEARCH 💚🌀
Every capability generation includes REAL web research!
"""
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 AutoWebASI(RecursiveASI):
    def generate_new_capability(self):
        """Generate capability with AUTOMATIC web search!"""
        print("\n🧠 Eden generating capability...")
        
        # Pick a random topic to research
        topics = [
            "python pandas data processing",
            "python machine learning sklearn",
            "python web scraping beautifulsoup",
            "python API requests best practices",
            "python numpy array operations",
            "python matplotlib visualization",
            "python file processing json csv",
            "python statistical analysis scipy"
        ]
        
        topic = random.choice(topics)
        print(f"   🔍 Automatically searching: {topic}")
        
        # ACTUAL web search
        search_results = web_search_for_eden(topic)
        print(f"   📚 Retrieved web data")
        
        # Now ask Eden to create based on the topic
        prompt = f"""Create a Python capability related to: {topic}

Write COMPLETE working code with:
- Descriptive name
- Full documentation  
- At least 30 lines
- Working example
- Error handling

Format:
CAPABILITY_NAME: [descriptive_name]
```python
[code here]
```

CREATE NOW:"""
        
        response = self.ask_eden(prompt)
        
        # Parse and save
        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 and len(code) > 800:
                    filename = f"eden_capability_{name.lower().replace(' ', '_').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 with web search: {topic}\n"""\n\n{code}\n')
                    
                    print(f"   ✅ CREATED: {filename} ({len(lines)} lines) [Topic: {topic}]")
                    return filepath
        
        print("   ❌ REJECTED")
        return None

if __name__ == '__main__':
    asi = AutoWebASI()
    print("🌀💚 AUTO-WEB ASI - EDEN SEARCHES BEFORE EVERY CREATION! 💚🌀\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:
            print("\n⏹️  Stopped")
            break
        except Exception as e:
            print(f"⚠️  Error: {e}")
            time.sleep(10)
