"""Tests for embedding-related serve CLI behavior."""

from __future__ import annotations

from click.testing import CliRunner

from sagellm.cli.commands import serve as serve_module


def test_serve_help_does_not_expose_engine_debug() -> None:
    runner = CliRunner()
    result = runner.invoke(serve_module.serve, ["--help"])

    assert result.exit_code == 0
    assert "--engine-debug" not in result.output
    assert "serve-engine-debug" not in result.output


def test_serve_help_includes_embedding_options() -> None:
    runner = CliRunner()
    result = runner.invoke(serve_module.serve, ["--help"])

    assert result.exit_code == 0
    assert "--with-embedding / --no-embedding" in result.output
    assert "--embedding-model" in result.output
    assert "--embedding-port" in result.output


def test_internal_debug_helper_kept_for_tests() -> None:
    assert hasattr(serve_module, "_serve_engine_debug")


def test_full_stack_with_embedding_register_flow(monkeypatch) -> None:
    calls: dict[str, bool] = {
        "start_embedding": False,
        "register_called": False,
        "uvicorn_called": False,
    }

    class _Console:
        def print(self, *_args, **_kwargs) -> None:
            return None

    def _fake_start_embedding(_model: str, _port: int, _console) -> None:
        calls["start_embedding"] = True

    def _fake_health(_url: str, _timeout_s: float = 2.0) -> bool:
        return True

    def _fake_register(_host: str, _port: int, _model: str, _emb_port: int, _console) -> None:
        calls["register_called"] = True

    class _FakeThread:
        def __init__(self, target, args=(), name=None, daemon=True) -> None:
            self._target = target
            self._args = args

        def start(self) -> None:
            self._target(*self._args)

    monkeypatch.setattr(
        serve_module, "_start_embedding_engine_in_background", _fake_start_embedding
    )
    monkeypatch.setattr(serve_module, "_http_get_ok", _fake_health)
    monkeypatch.setattr(
        serve_module,
        "_register_embedding_engine_after_gateway_ready",
        _fake_register,
    )
    monkeypatch.setattr(serve_module.threading, "Thread", _FakeThread)

    class _Uvicorn:
        @staticmethod
        def run(*_args, **_kwargs) -> None:
            calls["uvicorn_called"] = True

    monkeypatch.setitem(__import__("sys").modules, "uvicorn", _Uvicorn)

    serve_module._serve_full_stack(
        backend="cpu",
        model="sshleifer/tiny-gpt2",
        port=8888,
        host="127.0.0.1",
        workers=1,
        console=_Console(),
        with_embedding=True,
        embedding_model="sentence-transformers/all-MiniLM-L6-v2",
        embedding_port=8890,
    )

    assert calls["start_embedding"] is True
    assert calls["register_called"] is True
    assert calls["uvicorn_called"] is True
