"""lazy-mcp: A proxy tool that converts MCP servers to use lazy-loading pattern."""

__version__ = "2.1.9"

import os
import sys

BUNDLE_DIR = os.path.join(os.path.dirname(__file__), "bundle")
BUNDLE_JS = os.path.join(BUNDLE_DIR, "lazy-mcp.js")


def _find_node() -> str:
    """Find the node binary from nodejs-wheel."""
    try:
        from nodejs_wheel import executable  # type: ignore[import-untyped]

        bin_dir = os.path.join(os.path.dirname(executable.__file__), "bin")
        suffix = ".exe" if os.name == "nt" else ""
        node_path = os.path.join(bin_dir, "node" + suffix)
        if os.path.isfile(node_path):
            return node_path
    except ImportError:
        pass

    raise RuntimeError(
        "Could not find Node.js. Install nodejs-wheel: pip install nodejs-wheel"
    )


def main() -> None:
    """Entry point for the lazy-mcp CLI."""
    if not os.path.isfile(BUNDLE_JS):
        print(
            f"Error: Bundle not found at {BUNDLE_JS}\n"
            "This is a packaging bug — please report it.",
            file=sys.stderr,
        )
        sys.exit(1)

    node = _find_node()
    argv = [node, BUNDLE_JS] + sys.argv[1:]

    # Replace the current process with node (proper signal handling)
    if os.name == "nt":
        # Windows: no execvp, use subprocess
        import subprocess

        sys.exit(subprocess.call(argv))
    else:
        os.execvp(node, argv)
