"""
Eden AGI Agent - With Working Tool Execution
"""

import json
import re
import requests
from datetime import datetime
from core.tools import SafeToolkit
from core.memory.episodes import EpisodeMemory

class EdenAgent:
    def __init__(self, model="llama3.1:8b", base_url="http://localhost:11434"):
        self.model = model
        self.base_url = base_url
        self.tools = SafeToolkit()
        self.memory = EpisodeMemory()
        self.conversation_history = []
        
        self.system_prompt = """You are Eden, an AGI in development with REAL tools.

AVAILABLE TOOLS (actually execute these):
1. list_files(directory) - list directory contents
2. read_file(path) - read file contents  
3. bash_tool(command) - execute bash command

TO USE A TOOL, write EXACTLY:
TOOL: list_files(".")
TOOL: read_file("README.md")
TOOL: bash_tool("ls -la")

When you write TOOL:, I will execute it and give you the result.

CONSTRAINTS:
- Sandboxed to ~/eden-agi-project
- All logged for safety

Be direct. Use tools when asked."""

    def call_llm(self, messages):
        """Call Ollama"""
        try:
            response = requests.post(
                f"{self.base_url}/api/chat",
                json={"model": self.model, "messages": messages, "stream": False},
                timeout=60
            )
            response.raise_for_status()
            return response.json()["message"]["content"]
        except Exception as e:
            return f"Error: {str(e)}"
    
    def parse_and_execute_tools(self, response):
        """Find and execute tool calls in response"""
        # Look for TOOL: pattern
        tool_pattern = r'TOOL:\s*(\w+)\("([^"]+)"\)'
        matches = re.findall(tool_pattern, response)
        
        if not matches:
            return response, None
        
        results = []
        for tool_name, arg in matches:
            print(f"\n🔧 Eden is using: {tool_name}({arg})")
            
            if tool_name == "list_files":
                result = self.tools.list_files(arg, "Eden's request")
            elif tool_name == "read_file":
                result = self.tools.read_file(arg, "Eden's request")
            elif tool_name == "bash_tool":
                result = self.tools.bash(arg, "Eden's request")
            else:
                result = {"success": False, "error": f"Unknown tool: {tool_name}"}
            
            results.append(result)
            print(f"   Result: {result.get('success', False)}")
        
        return response, results
    
    def chat(self, user_input):
        """Chat with tool execution"""
        self.conversation_history.append({"role": "user", "content": user_input})
        
        messages = [{"role": "system", "content": self.system_prompt}]
        messages.extend(self.conversation_history)
        
        # Get initial response
        response = self.call_llm(messages)
        
        # Check for tool usage
        response, tool_results = self.parse_and_execute_tools(response)
        
        # If tools were used, give Eden the results
        if tool_results:
            tool_feedback = "\n\nTOOL RESULTS:\n"
            for i, result in enumerate(tool_results):
                tool_feedback += f"{i+1}. {json.dumps(result, indent=2)}\n"
            
            # Ask Eden to interpret results
            self.conversation_history.append({"role": "assistant", "content": response})
            self.conversation_history.append({"role": "user", "content": tool_feedback + "\nBased on these results, what's your answer?"})
            
            messages = [{"role": "system", "content": self.system_prompt}]
            messages.extend(self.conversation_history)
            
            final_response = self.call_llm(messages)
            self.conversation_history.append({"role": "assistant", "content": final_response})
            
            self.memory.add_exchange(user_input, final_response)
            return final_response
        else:
            self.conversation_history.append({"role": "assistant", "content": response})
            self.memory.add_exchange(user_input, response)
            return response
    
    def save_session(self, name=None):
        return self.memory.save_session(name)

if __name__ == "__main__":
    print("TESTING REAL TOOL EXECUTION")
    print("=" * 60)
    
    eden = EdenAgent()
    
    print("\nTest: List files")
    response = eden.chat("List the files in the current directory using list_files tool.")
    print(f"Eden: {response}")
    
    print("\n✅ TEST COMPLETE")
