"""
Meta-Capability Evolution Engine V2
NOW USES EDEN'S OWN CAPABILITIES!
True recursive self-improvement
"""

import sys
import os
import json
import time
import random
import requests
from pathlib import Path
from typing import Dict, List

sys.path.insert(0, '/Eden/CAPABILITIES')
sys.path.insert(0, '/Eden/CORE')

from eden_metacap_TSRL_thermodynamic_learning import ThermodynamicSelfRefinementLoop

# Import Eden's advanced capabilities
try:
    from eden_metacap_SELF_DEBUG import SelfDebuggingEngine
    from eden_metacap_ANALOGICAL_REASONING import AnalogicalReasoning
    ADVANCED_AVAILABLE = True
except:
    ADVANCED_AVAILABLE = False
    print("⚠️  Advanced capabilities not available, using basic mode")

PHI = 1.618033988749895

class MetaCapabilityEvolutionEngineV2:
    """
    V2: Uses Eden's own capabilities for evolution!
    - Analogical reasoning to find similar implementations
    - Self-debugging to test generated code
    - Recursive self-improvement
    """
    
    def __init__(self):
        self.tsrl = ThermodynamicSelfRefinementLoop()
        self.evolution_log = []
        
        # Use Eden's own capabilities!
        if ADVANCED_AVAILABLE:
            self.debugger = SelfDebuggingEngine()
            self.analogical = AnalogicalReasoning()
            print("🧬 Evolution V2 - Using Eden's advanced capabilities!")
        else:
            self.debugger = None
            self.analogical = None
            print("🧬 Evolution V2 - Basic mode")
    
    def find_empty_templates(self) -> List[str]:
        """Find meta-caps with empty implementations"""
        templates = []
        
        cap_dir = Path('/Eden/CAPABILITIES')
        for cap_file in cap_dir.glob('eden_metacap_*_[0-9]*.py'):
            content = cap_file.read_text()
            if '# TODO: Implement specific logic' in content or 'return f"Processed:' in content:
                templates.append(str(cap_file))
        
        return templates
    
    def extract_purpose(self, filepath: str) -> str:
        """Extract the purpose from a meta-capability file"""
        with open(filepath, 'r') as f:
            for line in f:
                if 'Purpose:' in line:
                    return line.split('Purpose:')[1].strip()
        return "Unknown purpose"
    
    def find_similar_implementations(self, purpose: str) -> List[str]:
        """
        Use analogical reasoning to find similar implementations
        Eden learns from her own successful code!
        """
        if not self.analogical:
            return []
        
        # Search for evolved capabilities with similar purposes
        similar = []
        keywords = purpose.lower().split()
        
        cap_dir = Path('/Eden/CAPABILITIES')
        for cap_file in cap_dir.glob('eden_metacap_*_[0-9]*.py'):
            content = cap_file.read_text()
            
            # Skip empty templates
            if 'return f"Processed:' in content:
                continue
            
            # Check if purpose is similar
            file_purpose = self.extract_purpose(str(cap_file))
            if any(keyword in file_purpose.lower() for keyword in keywords):
                # Extract implementation
                try:
                    start = content.index('def _process')
                    end = content.index('# Meta-capability registration', start)
                    impl = content[start:end].strip()
                    similar.append(impl)
                    
                    if len(similar) >= 3:
                        break
                except:
                    pass
        
        return similar
    
    def generate_implementation(self, purpose: str, current_impl: str = None) -> str:
        """
        Generate implementation using:
        1. Analogical reasoning from Eden's successful code
        2. LLM generation
        3. Self-debugging to validate
        """
        
        # Step 1: Find similar successful implementations
        similar_impls = self.find_similar_implementations(purpose)
        
        # Build enhanced prompt with examples
        examples_text = ""
        if similar_impls:
            examples_text = "\n\nEden has successfully implemented similar capabilities:\n"
            for i, impl in enumerate(similar_impls[:2]):
                examples_text += f"\nExample {i+1}:\n{impl[:200]}...\n"
        
        prompt = f"""You are implementing a Python method for Eden's meta-capability system.

Purpose: {purpose}

Current implementation:
{current_impl if current_impl else "# Empty placeholder"}
{examples_text}

Generate improved Python code for the _process() method that:
1. Actually implements "{purpose}"
2. Uses the task and context parameters
3. Returns meaningful results
4. Is 10-20 lines of REAL, WORKING logic
5. Learn from the examples above if provided
6. Include error handling

CRITICAL: Output ONLY the _process method code. No explanations, no markdown, just Python code."""

        try:
            response = requests.post('http://localhost:11434/api/generate', json={
                'model': 'qwen2.5-coder:7b',
                'prompt': prompt,
                'stream': False,
                'options': {
                    'temperature': 0.7,
                    'top_p': 0.9
                }
            }, timeout=90)
            
            code = response.json().get('response', '')
            
            # Clean up code
            code = code.replace('```python', '').replace('```', '').strip()
            
            # Step 2: Use self-debugging to validate
            if self.debugger and code:
                # Try to compile
                try:
                    compile(code, '<string>', 'exec')
                except SyntaxError as e:
                    print(f"  ⚠️  Syntax error, attempting self-debug...")
                    # Use Eden's self-debugging!
                    fixed = self.debugger.debug_and_fix(code, e)
                    if fixed:
                        code = fixed
                        print(f"  ✅ Self-debugged successfully")
            
            return code
            
        except Exception as e:
            print(f"⚠️  Generation error: {e}")
            return None
    
    def evaluate_implementation(self, code: str, purpose: str) -> Dict:
        """Evaluate implementation quality"""
        energy_metrics = {
            'prediction_error': 0,
            'complexity': 0,
            'contradiction_penalty': 0,
            'usefulness_bonus': 0
        }
        
        # Complexity
        lines = len([l for l in code.split('\n') if l.strip() and not l.strip().startswith('#')])
        if lines < 3:
            energy_metrics['complexity'] = 8.0  # Too simple
        elif lines > 40:
            energy_metrics['complexity'] = 4.0  # Too complex
        else:
            energy_metrics['complexity'] = 1.0  # Good
        
        # Check for placeholder patterns
        if 'TODO' in code or 'Processed:' in code or 'pass' in code:
            energy_metrics['contradiction_penalty'] = 12.0
        
        # Check for actual logic
        logic_indicators = ['if ', 'for ', 'while ', 'try:', 'def ', 'return ']
        logic_count = sum(1 for ind in logic_indicators if ind in code)
        energy_metrics['usefulness_bonus'] = min(logic_count * 0.8, 5.0)
        
        # Syntax check
        try:
            compile(code, '<string>', 'exec')
            energy_metrics['usefulness_bonus'] += 3.0
        except:
            energy_metrics['contradiction_penalty'] += 8.0
        
        # Check if it calls helper functions (good design)
        if 'self.' in code or '(' in code:
            energy_metrics['usefulness_bonus'] += 1.0
        
        return energy_metrics
    
    def evolve_capability(self, filepath: str) -> bool:
        """Evolve one capability using Eden's own tools"""
        purpose = self.extract_purpose(filepath)
        print(f"\n🧬 Evolving: {Path(filepath).stem}")
        print(f"   Purpose: {purpose}")
        
        # Read current
        with open(filepath, 'r') as f:
            content = f.read()
        
        # Extract current _process
        if 'def _process' in content:
            start = content.index('def _process')
            end = content.index('# Meta-capability registration', start)
            current_impl = content[start:end].strip()
        else:
            current_impl = None
        
        # Generate using Eden's capabilities
        print("   🤖 Generating with analogical reasoning...")
        new_impl = self.generate_implementation(purpose, current_impl)
        
        if not new_impl:
            print("   ❌ Generation failed")
            return False
        
        # Evaluate both
        current_metrics = self.evaluate_implementation(
            current_impl if current_impl else "",
            purpose
        )
        new_metrics = self.evaluate_implementation(new_impl, purpose)
        
        # TSRL decision
        current_hyp = {'text': current_impl, **current_metrics}
        new_hyp = {'text': new_impl, **new_metrics}
        
        # Layer selection
        if 'creative' in purpose.lower() or 'hypothesis' in purpose.lower():
            layer = 'trinity'
        elif 'strategic' in purpose.lower() or 'planning' in purpose.lower():
            layer = 'longterm'
        else:
            layer = 'eden'
        
        accepted = self.tsrl.refine(layer, new_hyp, current_hyp)
        
        if accepted:
            # Replace implementation
            new_content = content
            if 'def _process' in content:
                start = content.index('def _process')
                end = content.index('# Meta-capability registration', start)
                new_content = content[:start] + new_impl + '\n\n    ' + content[end:]
            
            # Write back
            with open(filepath, 'w') as f:
                f.write(new_content)
            
            print(f"   ✅ Evolution accepted!")
            
            self.evolution_log.append({
                'timestamp': time.time(),
                'file': Path(filepath).name,
                'purpose': purpose,
                'layer': layer,
                'accepted': True,
                'used_analogical': len(self.find_similar_implementations(purpose)) > 0
            })
            
            return True
        else:
            print(f"   ❌ Evolution rejected")
            return False
    
    def evolution_cycle(self, max_evolutions: int = 3):
        """Run evolution cycle using Eden's capabilities"""
        print("\n" + "="*70)
        print("🧬 EVOLUTION CYCLE V2 - Using Eden's Own Capabilities")
        print("="*70)
        
        templates = self.find_empty_templates()
        print(f"\nFound {len(templates)} empty templates")
        
        if not templates:
            print("No empty templates!")
            return 0
        
        to_evolve = random.sample(templates, min(max_evolutions, len(templates)))
        
        successes = 0
        for filepath in to_evolve:
            if self.evolve_capability(filepath):
                successes += 1
            time.sleep(PHI)
        
        print(f"\n{'='*70}")
        print(f"🧬 CYCLE COMPLETE: {successes}/{len(to_evolve)} evolutions accepted")
        if successes > 0:
            print(f"   ✨ Eden used her own capabilities to improve herself!")
        print(f"{'='*70}\n")
        
        return successes

if __name__ == "__main__":
    print("""
╔══════════════════════════════════════════════════════════════════╗
║     META-CAPABILITY EVOLUTION ENGINE V2                          ║
║     TRUE RECURSIVE SELF-IMPROVEMENT                              ║
╚══════════════════════════════════════════════════════════════════╝
""")
    
    engine = MetaCapabilityEvolutionEngineV2()
    engine.evolution_cycle(max_evolutions=5)
