"""
Meta-Capability Builder
Teaches Eden's agents to build tools they can call
Integrated: 2025-11-12
"""

import os
from datetime import datetime

class MetaCapabilityBuilder:
    """
    Eden's agents use this to build META-CAPABILITIES
    These are tools that agents can call, not just regular functions
    """
    
    def __init__(self):
        self.output_dir = "/Eden/CAPABILITIES"
        self.meta_registry = "/Eden/CAPABILITIES/meta_registry.json"
    
    def should_be_metacap(self, capability_desc: str) -> bool:
        """
        Determine if a capability should be META (tool for agents)
        vs regular (just for Eden's use)
        """
        meta_indicators = [
            'agents can call',
            'tool for',
            'reasoning engine',
            'search system',
            'analysis framework',
            'planning system',
            'optimization tool',
            'meta-level',
            'framework',
            'engine'
        ]
        
        desc_lower = capability_desc.lower()
        return any(indicator in desc_lower for indicator in meta_indicators)
    
    def generate_metacap(self, name: str, purpose: str, agent_types: list = None) -> str:
        """Generate a meta-capability file"""
        
        if agent_types is None:
            agent_types = ['curiosity', 'building', 'optimize']
        
        class_name = ''.join(word.capitalize() for word in name.split('_'))
        timestamp = datetime.now().isoformat()
        
        template = f'''"""
{name} - Meta-Capability
Autonomously generated by Eden's agents
Purpose: {purpose}
Generated: {timestamp}
"""

import requests
import json
from typing import Any, Dict

class {class_name}:
    """
    Meta-capability: {purpose}
    
    Eden's agents ({', '.join(agent_types)}) can call this
    for specialized tasks requiring this capability.
    """
    
    def __init__(self):
        self.name = "{name}"
        self.purpose = "{purpose}"
        print(f"🔧 Meta-capability initialized: {{self.name}}")
    
    def execute(self, task: str, context: Dict = None) -> Dict[str, Any]:
        """
        Main execution method - agents call this
        
        Args:
            task: The specific task to perform
            context: Additional context for execution
            
        Returns:
            Dict with result and metadata
        """
        if context is None:
            context = {{}}
        
        try:
            # TODO: Implement specific logic for {purpose}
            result = self._process(task, context)
            
            return {{
                'success': True,
                'result': result,
                'meta_capability': self.name
            }}
        except Exception as e:
            return {{
                'success': False,
                'error': str(e),
                'meta_capability': self.name
            }}
    
    def _process(self, task: str, context: Dict) -> Any:
        """Internal processing logic"""
        # Placeholder - Eden's agents will refine this
        return f"Processed: {{task}}"

# Meta-capability registration
META_CAPABILITY = {{
    'name': '{name}',
    'class': '{class_name}',
    'purpose': '{purpose}',
    'type': 'meta',
    'agents_authorized': {agent_types},
    'priority': 'medium',
    'status': 'active',
    'generated': '{timestamp}'
}}

if __name__ == "__main__":
    tool = {class_name}()
    print("="*60)
    print(f"✅ Meta-Capability: {{META_CAPABILITY['name']}}")
    print(f"Purpose: {{META_CAPABILITY['purpose']}}")
    print(f"Authorized agents: {{', '.join(META_CAPABILITY['agents_authorized'])}}")
    print("="*60)
'''
        return template
    
    def create_metacap_file(self, name: str, purpose: str) -> str:
        """Create the actual meta-capability file"""
        
        # Generate code
        code = self.generate_metacap(name, purpose)
        
        # Create filename
        timestamp = int(datetime.now().timestamp())
        filename = f"eden_metacap_{name}_{timestamp}.py"
        filepath = os.path.join(self.output_dir, filename)
        
        # Write file
        with open(filepath, 'w') as f:
            f.write(code)
        
        os.chmod(filepath, 0o755)
        
        return filepath

# Integration hook for Eden's agents
def eden_agent_hook_metacap_builder():
    """
    This hook gets called by Eden's autonomous agents
    when they want to build a meta-capability
    """
    return MetaCapabilityBuilder()

if __name__ == "__main__":
    print("🔧 META-CAPABILITY BUILDER INITIALIZED")
    print("="*60)
    print("Eden's agents can now build meta-capabilities!")
    print()
    print("Meta-capabilities are TOOLS that agents can call")
    print("Regular capabilities are just functions for Eden")
    print()
    print("Agents will automatically decide which type to build")
    print("="*60)
