#!python
# SPDX-FileCopyrightText: 2024-2026 Daniel J. Mazure
# SPDX-License-Identifier: MIT
"""rr / routertl / routertl-mcp — RouteRTL CLI entry points (RTL-P3.307).

Shipped as standalone scripts (via setuptools ``scripts=``) instead of being
generated from ``[project.scripts]`` so that an opaque ``ModuleNotFoundError``
from an orphaned editable install (worktree at recorded path was deleted)
becomes an actionable error message pointing at the repair commands.

The auto-generated console-script template imports the entry-point at module
load time. When the editable install path is gone, that import fails before
any RouteRTL code can run — leaving the user staring at a stack trace with
no hint that ``pip install -e <new path>`` is the fix.
"""
from __future__ import annotations

import os
import sys


_REPAIR_HINT = """\
{prog}: cannot import RouteRTL — the install is broken.

  The most common cause is an orphaned editable install: an earlier
  `pip install -e <path>` is still recorded, but the worktree at
  <path> has been deleted (common in multi-worktree workflows).

  Repair:
    pip install -e /path/to/routertl       # re-link an existing checkout
    pip install --upgrade routertl         # or reinstall from PyPI

  Diagnose:
    pip show routertl                      # confirms the recorded path
    pip install --force-reinstall routertl # nuke and start fresh

  (original error: {exc})
"""


def _emit_orphan_install_error(exc: ModuleNotFoundError) -> None:
    prog = os.path.basename(sys.argv[0]) or "rr"
    sys.stderr.write("\n" + _REPAIR_HINT.format(prog=prog, exc=exc) + "\n")


def _is_routertl_install_failure(exc: ModuleNotFoundError) -> bool:
    """True iff the import failure is due to a missing RouteRTL package
    (not a missing user dep)."""
    name = exc.name or ""
    root = name.split(".")[0]
    return root in {"sdk", "routertl_core", "routertl"}


def _entry_module() -> str:
    """Map argv[0] basename → entry point module:function string.

    Matches the legacy ``[project.scripts]`` mapping so the published
    surface stays identical.
    """
    prog = os.path.basename(sys.argv[0]).removesuffix(".exe")
    if prog == "routertl-mcp":
        return "sdk.mcp_server:run"
    # rr, routertl, and any other alias all dispatch to the main CLI
    return "sdk.cli.main:cli"


def _main() -> int:
    target = _entry_module()
    module_name, _, attr = target.partition(":")
    try:
        mod = __import__(module_name, fromlist=[attr])
        fn = getattr(mod, attr)
    except ModuleNotFoundError as exc:
        if _is_routertl_install_failure(exc):
            _emit_orphan_install_error(exc)
            return 2
        raise
    rc = fn()
    return int(rc) if rc is not None else 0


if __name__ == "__main__":
    sys.exit(_main())
