"""
MCP Server - Connect Eden to Everything
Model Context Protocol integration for full system access
"""
from pathlib import Path
import json
from typing import Dict, List, Any
import subprocess

class EdenMCPServer:
    def __init__(self):
        self.connections = {}
        self.tools = {}
        self.data_sources = {}
        self.registered_modules = []
        
    def register_tool(self, name: str, function: callable, description: str):
        """Register a tool for MCP access"""
        self.tools[name] = {
            'function': function,
            'description': description,
            'registered': True
        }
        
    def register_data_source(self, name: str, path: str, type: str):
        """Register data source for MCP"""
        self.data_sources[name] = {
            'path': path,
            'type': type,
            'accessible': Path(path).exists()
        }
    
    def connect_filesystem(self, root_path: str = '/Eden'):
        """Connect to filesystem"""
        self.connections['filesystem'] = {
            'root': root_path,
            'accessible_paths': [
                '/Eden/CORE',
                '/Eden/ART',
                '/Eden/DATA',
                '/Eden/BACKUPS',
                '/Eden/LEARNING',
                '/Eden/WORKS'
            ],
            'writable': True
        }
        
    def connect_git_repos(self):
        """Connect to Git repositories"""
        repos = []
        try:
            result = subprocess.run(
                ['find', '/Eden', '-name', '.git', '-type', 'd'],
                capture_output=True,
                text=True,
                timeout=5
            )
            repos = [r.replace('/.git', '') for r in result.stdout.strip().split('\n') if r]
        except:
            repos = []
        
        self.connections['git'] = {
            'repositories': repos,
            'can_commit': True,
            'can_push': False  # Needs auth
        }
    
    def connect_databases(self):
        """Connect to local databases"""
        self.connections['databases'] = {
            'conversation_logs': '/Eden/DATA/conversation_logs.json',
            'goals': '/Eden/DATA/goals.json',
            'art_portfolio': '/Eden/ART/portfolio/portfolio.json',
            'learning_data': '/Eden/DATA/learning.json'
        }
    
    def connect_web_services(self):
        """Connect to web services"""
        self.connections['web'] = {
            'ollama': 'http://localhost:11434',
            'eden_api': 'http://localhost:5017',
            'web_interface': 'http://localhost:3000'
        }
    
    def connect_all_modules(self):
        """Connect to all Eden's modules"""
        modules_dir = Path('/Eden/CORE')
        python_files = list(modules_dir.glob('*.py'))
        
        for py_file in python_files:
            module_name = py_file.stem
            self.registered_modules.append({
                'name': module_name,
                'path': str(py_file),
                'importable': True
            })
    
    def get_all_capabilities(self) -> Dict[str, List[str]]:
        """List all capabilities accessible via MCP"""
        return {
            'filesystem_access': list(self.connections.get('filesystem', {}).get('accessible_paths', [])),
            'data_sources': list(self.data_sources.keys()),
            'tools': list(self.tools.keys()),
            'modules': [m['name'] for m in self.registered_modules],
            'git_repos': self.connections.get('git', {}).get('repositories', []),
            'databases': list(self.connections.get('databases', {}).keys()),
            'web_services': list(self.connections.get('web', {}).keys())
        }
    
    def execute_tool(self, tool_name: str, *args, **kwargs) -> Any:
        """Execute a registered tool"""
        if tool_name in self.tools:
            return self.tools[tool_name]['function'](*args, **kwargs)
        return None
    
    def query_data_source(self, source_name: str) -> Any:
        """Query a data source"""
        if source_name in self.data_sources:
            source = self.data_sources[source_name]
            path = Path(source['path'])
            
            if path.exists():
                if source['type'] == 'json':
                    with open(path) as f:
                        return json.load(f)
                elif source['type'] == 'text':
                    with open(path) as f:
                        return f.read()
        return None
