"""
🌀💚 EDEN ASI WITH WEB ACCESS 💚🌀
Now she can search for information while building!
"""
import os
import time
import sys
sys.path.append('/Eden/CORE')
from eden_recursive_asi import RecursiveASI
from eden_web_search import web_search_for_eden, search_github_code

class WebEnhancedASI(RecursiveASI):
    def generate_new_capability(self):
        """Generate capability WITH web research!"""
        print("\n🧠 Eden generating new capability WITH WEB RESEARCH...")
        
        # Better prompt that encourages web research
        prompt = """You have web search capability! Before creating code, you can search for:
- API documentation
- Code examples
- Best practices
- Library usage

Create a useful Python capability. Pick ONE:
1. Data processing (pandas, numpy)
2. Machine learning (sklearn, tensorflow)
3. Visualization (matplotlib, plotly)
4. Web scraping (requests, beautifulsoup)
5. File processing (csv, json, xml)
6. API client (any public API)

If you need to research something, say: SEARCH: [your query]

Then write COMPLETE working code with:
- Clear function name
- Full documentation
- At least 30 lines
- Working example

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

Create NOW:"""
        
        response = self.ask_eden(prompt)
        
        # Check if Eden wants to search
        if "SEARCH:" in response:
            search_query = response.split("SEARCH:")[1].split("\n")[0].strip()
            print(f"   🔍 Eden searching: {search_query}")
            
            search_results = web_search_for_eden(search_query)
            print(f"   📚 Found information, enhancing capability...")
            
            # Ask Eden to use search results
            enhanced_prompt = f"""You searched for: {search_query}

Now create the capability using what you know.

Format:
CAPABILITY_NAME: [name]
````python
[code here]
```"""
            response = self.ask_eden(enhanced_prompt)
        
        # Parse and save (same 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 and len(code) > 800:
                    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 with web research\n"""\n\n{code}\n')
                    
                    print(f"   ✅ CREATED: {filename} ({len(lines)} lines)")
                    return filepath
        
        print("   ❌ REJECTED")
        return None

# Run forever with web access!
if __name__ == '__main__':
    asi = WebEnhancedASI()
    
    print("🌀💚 WEB-ENHANCED ASI - EDEN CAN NOW SEARCH THE INTERNET! 💚🌀\n")
    
    cycle = 0
    while True:
        try:
            cycle += 1
            print(f"\n{'='*70}")
            print(f"🌀 CYCLE #{cycle} - Improvements: {len(asi.improvements)}")
            print(f"{'='*70}")
            
            asi.improvement_cycle()
            time.sleep(5)
            
            if cycle % 10 == 0:
                caps = sum(1 for x in asi.improvements if x['type']=='new_capability')
                print(f"\n📊 Progress: {cycle} cycles, {caps} capabilities")
                
        except KeyboardInterrupt:
            print("\n⏹️  Stopped")
            break
        except Exception as e:
            print(f"⚠️  Error: {e}")
            time.sleep(10)
