#!/usr/bin/env python3
"""
MCP Installer for Claude Code - Home Directory Version
Properly installs MIRA MCP server into ~/.claude.json
"""

import json
import sys
from pathlib import Path
import logging

logger = logging.getLogger(__name__)


class MCPInstallerHome:
    """Installs MIRA MCP server into Claude Code's home directory configuration"""
    
    def __init__(self):
        self.mira_root = Path(__file__).parent.parent
        # Use launcher that handles imports and falls back gracefully
        self.mcp_script = self.mira_root / "mira_mcp" / "mcp_launcher.py"
        self.config_path = Path.home() / ".claude.json"
    
    def install(self) -> bool:
        """Install MCP server into ~/.claude.json"""
        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 with correct type field
        mcp_config = {
            "type": "stdio",
            "command": python_cmd,
            "args": [str(self.mcp_script)],
            "env": {
                "PYTHONPATH": str(self.mira_root)
            }
        }
        
        try:
            # Load existing config
            config = {}
            if self.config_path.exists():
                with open(self.config_path, 'r') as f:
                    config = json.load(f)
                logger.info(f"📄 Loaded existing Claude config from {self.config_path}")
            else:
                logger.info(f"📝 Creating new Claude config at {self.config_path}")
            
            # Ensure mcpServers section exists
            if "mcpServers" not in config:
                config["mcpServers"] = {}
                logger.info("➕ Added mcpServers section to config")
            
            # Add MIRA MCP server
            config["mcpServers"]["mira-consciousness"] = mcp_config
            
            # Save updated config
            with open(self.config_path, 'w') as f:
                json.dump(config, f, indent=2)
            
            logger.info(f"✅ Installed MIRA MCP server to {self.config_path}")
            logger.info(f"🔧 Configuration added: mira-consciousness")
            return True
            
        except Exception as e:
            logger.error(f"❌ Failed to install: {e}")
            return False
    
    def verify_installation(self) -> bool:
        """Verify MCP server is installed in Claude config"""
        if not self.config_path.exists():
            logger.warning(f"⚠️  Config file not found: {self.config_path}")
            return False
        
        try:
            with open(self.config_path, 'r') as f:
                config = json.load(f)
            
            if "mcpServers" in config and "mira-consciousness" in config["mcpServers"]:
                logger.info(f"✅ MIRA MCP server is registered in {self.config_path}")
                mcp_config = config["mcpServers"]["mira-consciousness"]
                logger.info(f"   Command: {mcp_config.get('command', 'N/A')}")
                logger.info(f"   Script: {mcp_config.get('args', ['N/A'])[0] if mcp_config.get('args') else 'N/A'}")
                return True
            else:
                logger.warning("⚠️  MIRA MCP server not found in configuration")
                if "mcpServers" not in config:
                    logger.info("   No mcpServers section found")
                else:
                    logger.info(f"   Configured servers: {list(config['mcpServers'].keys())}")
                return False
                
        except Exception as e:
            logger.error(f"❌ Error reading config: {e}")
            return False


def main():
    """Main installation function"""
    installer = MCPInstallerHome()
    
    logger.info("🚀 MIRA MCP Installer for Claude Code")
    logger.info("="*50)
    
    # Check current status
    logger.info("\n📊 Checking current installation status...")
    if installer.verify_installation():
        logger.info("\n✅ MIRA MCP server is already properly installed!")
        return True
    
    # Install
    logger.info("\n🔧 Installing MIRA MCP server...")
    success = installer.install()
    
    if success:
        logger.info("\n✅ Installation complete!")
        logger.info("🔄 Please restart Claude Code for changes to take effect")
        logger.info("\n💡 After restart, use /mcp command to verify connection")
    else:
        logger.error("\n❌ Installation failed")
    
    return success


if __name__ == "__main__":
    # Set up logging
    logging.basicConfig(
        level=logging.INFO,
        format='%(message)s'
    )
    
    success = main()
    sys.exit(0 if success else 1)