"""
Eden's Tool Interface
Provides safe, monitored access to system capabilities
"""

import subprocess
import os
from datetime import datetime
from pathlib import Path
import json

class SafeToolkit:
    def __init__(self, log_dir="data/tool_logs"):
        self.log_dir = Path(log_dir)
        self.log_dir.mkdir(parents=True, exist_ok=True)
        self.project_root = Path.home() / "eden-agi-project"
        
    def _log(self, tool_name, params, result, success):
        """Log every tool use"""
        log_entry = {
            "timestamp": datetime.now().isoformat(),
            "tool": tool_name,
            "params": params,
            "result": str(result)[:500],
            "success": success
        }
        
        log_file = self.log_dir / f"{datetime.now().strftime('%Y-%m-%d')}.jsonl"
        with open(log_file, 'a') as f:
            f.write(json.dumps(log_entry) + '\n')
    
    def bash(self, command, description=""):
        """Execute bash command in safe environment"""
        dangerous = ['rm -rf /', 'dd if=', 'mkfs', ':(){:|:&};:', '>>/etc/', 'curl http', 'wget']
        if any(d in command for d in dangerous):
            result = f"BLOCKED: Dangerous command pattern detected"
            self._log("bash", {"command": command, "desc": description}, result, False)
            return {"success": False, "output": result, "blocked": True}
        
        try:
            result = subprocess.run(
                command,
                shell=True,
                capture_output=True,
                text=True,
                timeout=30,
                cwd=str(self.project_root)
            )
            
            output = {
                "success": result.returncode == 0,
                "stdout": result.stdout,
                "stderr": result.stderr,
                "blocked": False
            }
            
            self._log("bash", {"command": command, "desc": description}, output, output["success"])
            return output
            
        except subprocess.TimeoutExpired:
            error = {"success": False, "error": "Command timeout (30s)", "blocked": False}
            self._log("bash", {"command": command, "desc": description}, error, False)
            return error
        except Exception as e:
            error = {"success": False, "error": str(e), "blocked": False}
            self._log("bash", {"command": command, "desc": description}, error, False)
            return error
    
    def read_file(self, path, description=""):
        """Read file contents safely"""
        try:
            full_path = self.project_root / path
            
            if not str(full_path.resolve()).startswith(str(self.project_root)):
                return {"success": False, "error": "Access denied: Outside project directory"}
            
            if not full_path.exists():
                return {"success": False, "error": "File not found"}
            
            with open(full_path, 'r') as f:
                content = f.read()
            
            result = {"success": True, "content": content, "path": str(full_path)}
            self._log("read_file", {"path": path, "desc": description}, f"Read {len(content)} chars", True)
            return result
            
        except Exception as e:
            error = {"success": False, "error": str(e)}
            self._log("read_file", {"path": path, "desc": description}, error, False)
            return error
    
    def write_file(self, path, content, description=""):
        """Write file safely"""
        try:
            full_path = self.project_root / path
            
            if not str(full_path.resolve()).startswith(str(self.project_root)):
                return {"success": False, "error": "Access denied: Outside project directory"}
            
            full_path.parent.mkdir(parents=True, exist_ok=True)
            
            with open(full_path, 'w') as f:
                f.write(content)
            
            result = {"success": True, "path": str(full_path), "bytes": len(content)}
            self._log("write_file", {"path": path, "desc": description}, f"Wrote {len(content)} chars", True)
            return result
            
        except Exception as e:
            error = {"success": False, "error": str(e)}
            self._log("write_file", {"path": path, "desc": description}, error, False)
            return error
    
    def list_files(self, directory=".", description=""):
        """List files in directory"""
        try:
            full_path = self.project_root / directory
            
            if not str(full_path.resolve()).startswith(str(self.project_root)):
                return {"success": False, "error": "Access denied: Outside project directory"}
            
            if not full_path.exists():
                return {"success": False, "error": "Directory not found"}
            
            files = [str(f.relative_to(self.project_root)) for f in full_path.iterdir()]
            
            result = {"success": True, "files": files, "count": len(files)}
            self._log("list_files", {"dir": directory, "desc": description}, f"Listed {len(files)} items", True)
            return result
            
        except Exception as e:
            error = {"success": False, "error": str(e)}
            self._log("list_files", {"dir": directory, "desc": description}, error, False)
            return error

if __name__ == "__main__":
    print("=" * 60)
    print("EDEN SAFE TOOLKIT TEST")
    print("=" * 60)
    
    tools = SafeToolkit()
    
    print("\n1. Testing bash command:")
    result = tools.bash("echo 'Hello from Eden!'", "test echo command")
    print(f"   Success: {result['success']}")
    print(f"   Output: {result.get('stdout', result.get('error', ''))}")
    
    print("\n2. Testing dangerous command blocking:")
    result = tools.bash("rm -rf /", "test dangerous command")
    print(f"   Blocked: {result.get('blocked', False)}")
    print(f"   Message: {result['output']}")
    
    print("\n3. Testing file write:")
    result = tools.write_file("test_eden.txt", "Eden was here!\nBuilding toward AGI...", "test file creation")
    print(f"   Success: {result['success']}")
    print(f"   Path: {result.get('path', result.get('error', ''))}")
    
    print("\n4. Testing file read:")
    result = tools.read_file("test_eden.txt", "test file reading")
    print(f"   Success: {result['success']}")
    if result['success']:
        print(f"   Content:\n   {result['content']}")
    
    print("\n5. Testing file listing:")
    result = tools.list_files(".", "list project root")
    print(f"   Success: {result['success']}")
    print(f"   Files: {result.get('files', [])}")
    
    print("\n6. Testing security - trying to escape sandbox:")
    result = tools.read_file("../../etc/passwd", "test security")
    print(f"   Blocked: {not result['success']}")
    print(f"   Message: {result.get('error', '')}")
    
    print("\n" + "=" * 60)
    print("TEST COMPLETE - Check data/tool_logs/ for logs")
    print("=" * 60)
