"""
🌀💚 EDEN CONTINUOUS ASI - IMPROVED PROMPTS 💚🌀
"""
import os
import time
import signal
import sys
sys.path.append('/Eden/CORE')
from eden_recursive_asi import RecursiveASI

class ImprovedASI(RecursiveASI):
    def generate_new_capability(self):
        """Improved capability generation with better prompts"""
        print("\n🧠 Eden generating new capability...")
        
        # Better, more specific prompt
        prompt = """Create a useful Python function that adds real value. Pick ONE from these ideas:

1. Data analysis helper (statistics, graphing)
2. File processing utility (parsing, formatting)
3. Algorithm implementation (sorting, searching, optimization)
4. API client (weather, news, etc)
5. Math/science calculator

Write COMPLETE working code with:
- Clear function name
- Docstring
- At least 25 lines
- Example usage at bottom

Format EXACTLY like this:
CAPABILITY_NAME: [short_name]
```python
def your_function():
    \"\"\"What it does\"\"\"
    # implementation here
    pass

# Example usage
if __name__ == '__main__':
    result = your_function()
    print(result)
```

Create NOW:"""
        
        response = self.ask_eden(prompt)
        
        # Parse with better error handling
        if "```python" in response:
            start = response.find("```python") + 9
            end = response.find("```", start)
            if end > start:
                code = response[start:end].strip()
                
                # Extract name
                name = "unnamed"
                if "CAPABILITY_NAME:" in response:
                    name = response.split("CAPABILITY_NAME:")[1].split("\n")[0].strip()
                
                # Quality check
                lines = code.split('\n')
                if len(lines) >= 25 and len(code) > 600:
                    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\n"""\n\n{code}\n')
                    
                    print(f"   ✅ CREATED: {filename} ({len(lines)} lines)")
                    return filepath
        
        print("   ❌ REJECTED: Invalid format or too short")
        return None

# Run forever
if __name__ == '__main__':
    asi = ImprovedASI()
    asi.running = True
    
    print("🌀💚 IMPROVED ASI - RUNNING FOREVER 💚🌀\n")
    
    cycle = 0
    while True:
        try:
            cycle += 1
            print(f"\n{'='*70}")
            print(f"🌀 CYCLE #{cycle} - Total 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 by user")
            break
        except Exception as e:
            print(f"⚠️  Error: {e}, continuing...")
            time.sleep(10)
