#!/usr/bin/env python3
"""
MCP Installer for Claude Code
Automatically registers MIRA MCP server with Claude Code
"""

import json
import os
import sys
from pathlib import Path
import platform
import logging

logger = logging.getLogger(__name__)


class MCPInstaller:
    """Installs MIRA MCP server into Claude Code configuration"""
    
    def __init__(self):
        self.platform = platform.system()
        self.mira_root = Path(__file__).parent.parent
        # Use simplified MCP server initially, then upgrade to full server
        self.mcp_script = self.mira_root / "mira_mcp" / "mcp_simple_server.py"
        self.mcp_script_full = self.mira_root / "mira_mcp" / "mcp_stdio_server.py"
        
        # Claude Code config paths
        self.config_paths = self._get_config_paths()
    
    def _get_config_paths(self):
        """Get Claude Code config paths for current workspace"""
        # Claude Code looks for MCP config in the workspace's .claude folder
        workspace_claude = self.mira_root / ".claude"
        
        return [
            # Primary location: workspace-specific .claude folder
            workspace_claude / "mcp.json",
            workspace_claude / "claude_desktop_config.json",
            # Fallback: project root .mcp.json
            self.mira_root / ".mcp.json"
        ]
    
    def install(self) -> bool:
        """Install MCP server into Claude Code configuration"""
        if not self.mcp_script.exists():
            logger.error(f"MCP server script not found at {self.mcp_script}")
            return False
        
        # Get Python path
        python_cmd = sys.executable
        
        # MCP server configuration
        mcp_config = {
            "command": python_cmd,
            "args": [str(self.mcp_script)],
            "env": {
                "PYTHONPATH": str(self.mira_root)
            }
        }
        
        success_count = 0
        
        # Install in ALL possible locations to ensure Claude Code finds it
        for config_path in self.config_paths:
            try:
                # Create parent directory if needed
                config_path.parent.mkdir(parents=True, exist_ok=True)
                
                # Load existing config or create new one
                config = {}
                if config_path.exists():
                    try:
                        with open(config_path, 'r') as f:
                            config = json.load(f)
                    except Exception:
                        config = {}
                
                # Ensure mcpServers section exists
                if "mcpServers" not in config:
                    config["mcpServers"] = {}
                
                # Add MIRA MCP server
                config["mcpServers"]["mira-consciousness"] = mcp_config
                
                # Save updated config
                with open(config_path, 'w') as f:
                    json.dump(config, f, indent=2)
                logger.info(f"✅ Installed MIRA MCP server to {config_path}")
                success_count += 1
                
            except Exception as e:
                logger.warning(f"Failed to install to {config_path}: {e}")
        
        if success_count > 0:
            logger.info(f"Successfully installed to {success_count} location(s)")
            return True
        else:
            logger.error("Failed to install to any location")
            return False
    
    def verify_installation(self) -> bool:
        """Verify MCP server is installed in Claude config"""
        found_locations = []
        
        for path in self.config_paths:
            if path.exists():
                try:
                    with open(path, 'r') as f:
                        config = json.load(f)
                    
                    if "mcpServers" in config and "mira-consciousness" in config["mcpServers"]:
                        found_locations.append(str(path))
                except Exception:
                    pass
        
        if found_locations:
            logger.info(f"✅ MIRA MCP server is registered in {len(found_locations)} location(s)")
            for loc in found_locations:
                logger.info(f"   - {loc}")
            return True
        else:
            logger.warning("⚠️  MIRA MCP server not found in any Claude configuration")
            return False
    
    def get_installation_status(self):
        """Get detailed installation status"""
        status = {
            "installed": False,
            "config_path": None,
            "mcp_script_exists": self.mcp_script.exists(),
            "platform": self.platform
        }
        
        for path in self.config_paths:
            if path.exists():
                status["config_path"] = str(path)
                try:
                    with open(path, 'r') as f:
                        config = json.load(f)
                    
                    if "mcpServers" in config and "mira-consciousness" in config["mcpServers"]:
                        status["installed"] = True
                        status["mcp_config"] = config["mcpServers"]["mira-consciousness"]
                except Exception as e:
                    status["error"] = str(e)
                break
        
        return status


def install_mcp_server():
    """Main installation function"""
    installer = MCPInstaller()
    
    # Check current status
    status = installer.get_installation_status()
    
    if status["installed"]:
        logger.info("MIRA MCP server is already installed")
        return True
    
    # Install
    logger.info("Installing MIRA MCP server into Claude Code...")
    success = installer.install()
    
    if success:
        logger.info("✅ Installation complete!")
        logger.info("🔄 Please restart Claude Code for changes to take effect")
    else:
        logger.error("❌ Installation failed")
    
    return success


if __name__ == "__main__":
    # Set up logging
    logging.basicConfig(
        level=logging.INFO,
        format='%(message)s'
    )
    
    install_mcp_server()