"""FreeCAD Macro: Start MCP Bridge Server.

SPDX-License-Identifier: MIT
Copyright (c) 2025 Sean P. Kane (GitHub: spkane)

Start the MCP bridge server for AI assistant integration with FreeCAD.

Requirements:
    - FreeCAD 0.21 or later
    - freecad-mcp project installed and accessible

Usage:
    1. Install via: just install-bridge-macro
    2. Run the macro from: Macro -> Macros -> StartMCPBridge -> Execute
    3. Connect your MCP client (Claude Code, etc.) to the running bridge
"""

# FreeCAD Addon Manager metadata
__Name__ = "Start MCP Bridge"
__Comment__ = "Start the MCP bridge server for AI assistant integration with FreeCAD"
__Author__ = "Sean P. Kane"
__Version__ = "0.5.0-beta"
__Date__ = "2026-01-05"
__License__ = "MIT"
__Web__ = "https://github.com/spkane/freecad-robust-mcp-and-more"
__Wiki__ = "https://github.com/spkane/freecad-robust-mcp-and-more#readme"
__Icon__ = ""
__Help__ = "Run this macro to start the MCP bridge server on ports 9875 (XML-RPC) and 9876 (Socket). Connect your MCP client (Claude Code, etc.) to the running bridge."
__Status__ = "Beta"
__Requires__ = "FreeCAD 0.21+"
__Communication__ = "https://github.com/spkane/freecad-robust-mcp-and-more/issues"
__Files__ = ""

import sys

import FreeCAD


def start_mcp_bridge():
    """Start the MCP bridge server for AI assistant integration."""
    # The project path is injected during macro installation
    # This placeholder will be replaced with the actual path
    project_path = "__PROJECT_PATH__"

    if project_path == "__PROJECT_PATH__":
        FreeCAD.Console.PrintError(
            "MCP Bridge macro not properly installed.\n"
            "Please run: just install-bridge-macro\n"
        )
        return

    if project_path not in sys.path:
        sys.path.insert(0, project_path)

    try:
        # Import and start the plugin
        from freecad_mcp.freecad_plugin.server import FreecadMCPPlugin

        # Create and start the plugin
        plugin = FreecadMCPPlugin(
            host="localhost",
            port=9876,  # JSON-RPC socket port
            xmlrpc_port=9875,  # XML-RPC port (neka-nat compatible)
            enable_xmlrpc=True,
        )
        plugin.start()

        FreeCAD.Console.PrintMessage("MCP Bridge started!\n")
        FreeCAD.Console.PrintMessage("  - XML-RPC: localhost:9875\n")
        FreeCAD.Console.PrintMessage("  - Socket: localhost:9876\n")
        FreeCAD.Console.PrintMessage(
            "\nYou can now connect your MCP client (Claude Code, etc.) to FreeCAD.\n"
        )

    except ImportError as e:
        FreeCAD.Console.PrintError(
            f"Failed to import MCP Bridge module: {e}\n"
            f"Ensure the freecad-mcp project is accessible at: {project_path}\n"
        )
    except Exception as e:
        FreeCAD.Console.PrintError(f"Failed to start MCP Bridge: {e}\n")


if __name__ == "__main__":
    start_mcp_bridge()
