"""CLI entrypoint for g-gremlin-dynamics-mcp."""

from __future__ import annotations

import argparse
import sys

from g_gremlin_dynamics_mcp import __version__
from g_gremlin_dynamics_mcp.runner import check_gremlin_version, launch_gremlin_mcp


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Launch g-gremlin Dynamics 365 / Dataverse MCP server (stdio).")
    parser.add_argument(
        "--enable-writes",
        action="store_true",
        help="Expose write tools (still requires plan_hash on apply calls).",
    )
    parser.add_argument(
        "--profile",
        default=None,
        help="Default Dynamics profile passed to g-gremlin mcp serve-dynamics.",
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Validate g-gremlin availability/version and exit.",
    )
    parser.add_argument(
        "--version",
        action="store_true",
        help="Print launcher version and exit.",
    )
    return parser


def main(argv: list[str] | None = None) -> int:
    parser = _build_parser()
    args = parser.parse_args(argv)

    if args.version:
        print(__version__)
        return 0

    try:
        detected = check_gremlin_version()
    except RuntimeError as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 2

    if args.check:
        print(f"g-gremlin {detected} detected")
        return 0

    try:
        return launch_gremlin_mcp(
            enable_writes=bool(args.enable_writes),
            profile=str(args.profile).strip() if args.profile else None,
        )
    except OSError as exc:
        print(f"Error launching g-gremlin mcp serve-dynamics: {exc}", file=sys.stderr)
        return 2


if __name__ == "__main__":
    raise SystemExit(main())
