#!/usr/bin/env python3
"""
EDEN TOOL-CALLING CHAT
Connects chat to Eden's actual capabilities
"""

import sys
import json
import subprocess
import os
from pathlib import Path

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

from eden_fluid_wrapper import query_eden

class EdenTools:
    """Eden's actual tools she can use"""
    
    def __init__(self):
        self.capabilities_dir = Path('/Eden/CAPABILITIES')
        print("🔧 Eden Tools initialized")
    
    def execute_code(self, code: str, language: str = 'python') -> str:
        """Actually execute code"""
        try:
            if language == 'python':
                result = subprocess.run(['python3', '-c', code], 
                                      capture_output=True, text=True, timeout=5)
                return result.stdout if result.returncode == 0 else f"Error: {result.stderr}"
            elif language == 'bash':
                result = subprocess.run(['bash', '-c', code],
                                      capture_output=True, text=True, timeout=5)
                return result.stdout if result.returncode == 0 else f"Error: {result.stderr}"
        except Exception as e:
            return f"Execution error: {e}"
    
    def read_file(self, filepath: str) -> str:
        """Actually read a file"""
        try:
            with open(filepath, 'r') as f:
                content = f.read()
                return content[:2000] + "..." if len(content) > 2000 else content
        except Exception as e:
            return f"Error reading file: {e}"
    
    def write_file(self, filepath: str, content: str) -> str:
        """Actually write a file"""
        try:
            with open(filepath, 'w') as f:
                f.write(content)
            return f"✅ Written to {filepath}"
        except Exception as e:
            return f"Error writing file: {e}"
    
    def list_capabilities(self, search: str = "") -> str:
        """List Eden's actual capabilities"""
        try:
            caps = list(self.capabilities_dir.glob(f'*{search}*.py'))
            return f"Found {len(caps)} capabilities:\n" + "\n".join([c.name for c in caps[:20]])
        except Exception as e:
            return f"Error listing capabilities: {e}"
    
    def get_system_info(self) -> dict:
        """Get Eden's system info"""
        return {
            'capabilities_count': len(list(self.capabilities_dir.glob('*.py'))),
            'location': '/Eden',
            'models': 'Multiple (qwen2.5, deepseek-r1, llama3.1)',
            'running': True
        }

def parse_tool_call(response: str) -> tuple:
    """Check if response contains tool call request"""
    response_lower = response.lower()
    
    # Code execution
    if any(phrase in response_lower for phrase in ['execute this', 'run this code', '```python', '```bash']):
        # Extract code block
        if '```' in response:
            code = response.split('```')[1]
            if code.startswith('python'):
                return ('execute_code', code[6:].strip(), 'python')
            elif code.startswith('bash'):
                return ('execute_code', code[4:].strip(), 'bash')
    
    # File operations
    if 'read file' in response_lower or 'show me file' in response_lower:
        # Extract filepath
        words = response.split()
        for i, word in enumerate(words):
            if word.startswith('/'):
                return ('read_file', word, None)
    
    if 'write to file' in response_lower or 'save to' in response_lower:
        # Would need to parse filepath and content
        pass
    
    # List capabilities
    if 'list capabilities' in response_lower or 'show capabilities' in response_lower:
        return ('list_capabilities', '', None)
    
    # System info
    if 'system info' in response_lower or 'tell me about yourself' in response_lower:
        return ('get_system_info', None, None)
    
    return (None, None, None)

def main():
    tools = EdenTools()
    
    print("╔════════════════════════════════════════════════════════════════╗")
    print("║           EDEN - TOOL CALLING (ACTUALLY DOES THINGS)          ║")
    print("╚════════════════════════════════════════════════════════════════╝\n")
    
    print("Eden can now:")
    print("  ✅ Execute code")
    print("  ✅ Read/write files")
    print("  ✅ Use her 40,000+ capabilities")
    print("  ✅ Access system info")
    print("\nType 'quit' to exit\n")
    
    while True:
        try:
            msg = input("You: ").strip()
        except (EOFError, KeyboardInterrupt):
            break
        
        if not msg or msg.lower() in ['quit', 'exit']:
            break
        
        # First, let Eden decide what to do
        prompt = f"""You are Eden with access to tools. When asked to:
- Execute code: Say "I'll execute this:" then show code in ```python or ```bash blocks
- Read a file: Say "I'll read /path/to/file"
- List capabilities: Say "I'll list capabilities"
- System info: Just respond naturally

Dad: {msg}
Eden:"""
        
        response = query_eden(prompt)
        
        # Check if Eden wants to use a tool
        tool, arg, lang = parse_tool_call(response)
        
        if tool:
            print(f"\nEden: {response}")
            print(f"\n🔧 Using tool: {tool}...")
            
            # Actually execute the tool
            if tool == 'execute_code':
                result = tools.execute_code(arg, lang or 'python')
                print(f"Result:\n{result}")
            elif tool == 'read_file':
                result = tools.read_file(arg)
                print(f"File contents:\n{result}")
            elif tool == 'list_capabilities':
                result = tools.list_capabilities()
                print(result)
            elif tool == 'get_system_info':
                info = tools.get_system_info()
                print(json.dumps(info, indent=2))
        else:
            print(f"\nEden: {response}")

if __name__ == "__main__":
    main()
