from __future__ import annotations

import subprocess

import pytest

from g_gremlin_dynamics_mcp import runner


def test_build_command_default() -> None:
    assert runner.build_command(enable_writes=False) == ["mcp", "serve-dynamics"]


def test_build_command_with_writes() -> None:
    assert runner.build_command(enable_writes=True) == ["mcp", "serve-dynamics", "--enable-writes"]


def test_build_command_with_profile() -> None:
    assert runner.build_command(enable_writes=False, profile="prod") == ["mcp", "serve-dynamics", "--profile", "prod"]


def test_check_gremlin_version_accepts_current(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(runner, "_find_gremlin", lambda: "g-gremlin")
    monkeypatch.setattr(
        subprocess,
        "run",
        lambda *_args, **_kwargs: subprocess.CompletedProcess(args=["g-gremlin"], returncode=0, stdout="0.1.14\n", stderr=""),
    )
    assert runner.check_gremlin_version() == "0.1.14"


def test_check_gremlin_version_rejects_old(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(runner, "_find_gremlin", lambda: "g-gremlin")
    monkeypatch.setattr(
        subprocess,
        "run",
        lambda *_args, **_kwargs: subprocess.CompletedProcess(args=["g-gremlin"], returncode=0, stdout="0.1.0\n", stderr=""),
    )
    with pytest.raises(RuntimeError, match=">=0.1.14 required"):
        runner.check_gremlin_version()


def test_launch_gremlin_mcp_uses_execv_on_posix(monkeypatch: pytest.MonkeyPatch) -> None:
    calls: dict[str, object] = {}

    monkeypatch.setattr(runner, "_find_gremlin", lambda: "C:/bin/g-gremlin")
    monkeypatch.setattr(runner.os, "name", "posix")

    def _fake_execv(path: str, args: list[str]) -> None:
        calls["path"] = path
        calls["args"] = args

    monkeypatch.setattr(runner.os, "execv", _fake_execv)
    rc = runner.launch_gremlin_mcp(enable_writes=True, profile="alpha")

    assert rc == 0
    assert calls["path"] == "C:/bin/g-gremlin"
    assert calls["args"] == ["C:/bin/g-gremlin", "mcp", "serve-dynamics", "--profile", "alpha", "--enable-writes"]


def test_launch_gremlin_mcp_uses_subprocess_on_windows(monkeypatch: pytest.MonkeyPatch) -> None:
    calls: dict[str, object] = {}

    monkeypatch.setattr(runner, "_find_gremlin", lambda: "C:/bin/g-gremlin.exe")
    monkeypatch.setattr(runner.os, "name", "nt")

    def _fake_run(args: list[str], check: bool = False):
        calls["args"] = args
        calls["check"] = check
        return subprocess.CompletedProcess(args=args, returncode=7, stdout="", stderr="")

    monkeypatch.setattr(runner.subprocess, "run", _fake_run)
    rc = runner.launch_gremlin_mcp(enable_writes=False, profile="prod")

    assert rc == 7
    assert calls["args"] == ["C:/bin/g-gremlin.exe", "mcp", "serve-dynamics", "--profile", "prod"]
    assert calls["check"] is False
