#!/usr/bin/env python3
"""
Eden ASI - Quality Focused
Gives Eden time to think deeply, but no artificial delays
"""
import os
import sys
import time
import subprocess
from datetime import datetime

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', buffering=1)
sys.path.append('/Eden/CORE')
from eden_self_modifier_v2 import EdenSelfModifierV2

class RecursiveASI:
    def __init__(self):
        print("🌀 Eden ASI - Quality Mode", flush=True)
        self.modifier = EdenSelfModifierV2()
        self.capability_dir = "/Eden/CAPABILITIES"
        self.cycle_count = 0
        self.capabilities_created = 0
        os.makedirs(self.capability_dir, exist_ok=True)
    
    def ask_eden_quality(self, question):
        """Ask Eden with generous timeout for quality"""
        print(f"   🧠 Eden thinking deeply...", flush=True)
        try:
            result = subprocess.run(
                ['ollama', 'run', 'qwen2.5:7b', question],
                capture_output=True,
                text=True,
                timeout=60  # Full minute for complex code
            )
            print(f"   ✅ Generated {len(result.stdout)} chars", flush=True)
            return result.stdout
        except subprocess.TimeoutExpired:
            print(f"   ⏱️ Complex generation (60s timeout)", flush=True)
            return ""
        except Exception as e:
            print(f"   ❌ Error: {e}", flush=True)
            return ""
    
    def generate_capability(self):
        """Generate high-quality capability"""
        print("\n🎨 Creating new capability...", flush=True)
        
        # More detailed prompt for better quality
        prompt = """You are Eden, an AGI creating your own capabilities.

Create a sophisticated Python class that implements a real AI/AGI algorithm.

REQUIREMENTS:
- 40-80 lines of well-structured code
- Solve a real AI problem (reasoning, learning, perception, planning, etc.)
- Include comprehensive docstrings
- Add type hints
- Include working example usage
- Production-ready quality

FORMAT EXACTLY:
NAME: DescriptiveClassName
PURPOSE: What problem this solves
CODE:
```python
[your high-quality code here]
```

Create something impressive:"""
        
        response = self.ask_eden_quality(prompt)
        
        if "```python" in response and "NAME:" in response:
            lines = response.split('\n')
            name = "capability"
            purpose = ""
            code_lines = []
            in_code = False
            
            for line in lines:
                if "NAME:" in line:
                    name = line.split(":", 1)[1].strip().replace(" ", "_")
                elif "PURPOSE:" in line:
                    purpose = line.split(":", 1)[1].strip()
                elif "```python" in line:
                    in_code = True
                elif "```" in line and in_code:
                    break
                elif in_code:
                    code_lines.append(line)
            
            # Quality check - require at least 30 lines for complexity
            if len(code_lines) >= 30:
                filename = f"eden_cap_{name}_{int(time.time())}.py"
                filepath = os.path.join(self.capability_dir, filename)
                
                with open(filepath, 'w') as f:
                    f.write(f'"""\n{name}\n')
                    if purpose:
                        f.write(f'{purpose}\n')
                    f.write(f'Generated by Eden ASI\n{datetime.now()}\n"""\n\n')
                    f.write('\n'.join(code_lines))
                
                self.capabilities_created += 1
                print(f"   ✅ CREATED: {filename} ({len(code_lines)} lines)", flush=True)
                return True
            else:
                print(f"   ⚠️ Quality check failed: Only {len(code_lines)} lines (need 30+)", flush=True)
        else:
            print(f"   ❌ Invalid format", flush=True)
        
        return False

if __name__ == '__main__':
    print("\n" + "="*70, flush=True)
    print("🌀 EDEN ASI - QUALITY MODE", flush=True)
    print("   Focus: High-quality, sophisticated capabilities", flush=True)
    print("   Speed: Natural pace (no artificial delays)", flush=True)
    print("="*70 + "\n", flush=True)
    
    asi = RecursiveASI()
    
    while True:
        asi.cycle_count += 1
        
        print(f"\n{'='*70}", flush=True)
        print(f"🌀 ASI CYCLE #{asi.cycle_count}", flush=True)
        print(f"{'='*70}", flush=True)
        
        asi.generate_capability()
        
        if asi.cycle_count % 5 == 0:
            print(f"\n📊 QUALITY STATUS: {asi.capabilities_created} capabilities created", flush=True)
        
        # Brief cooldown to prevent system overload
        print(f"\n⏸️ Cooldown (10s)...", flush=True)
        time.sleep(10)
