"""Runtime regression tests for edge server entrypoint."""

from __future__ import annotations

import argparse
import importlib
import sys
import types


def _import_server_with_fake_ports(monkeypatch):
    """Import server module with a fake SagePorts provider for isolated tests."""
    ports_module = types.ModuleType("sage.common.config.ports")

    class _FakeSagePorts:
        EDGE_DEFAULT = 8899

    ports_module.SagePorts = _FakeSagePorts

    monkeypatch.setitem(sys.modules, "sage.common.config.ports", ports_module)
    sys.modules.pop("sage.edge.server", None)
    return importlib.import_module("sage.edge.server")


def test_server_main_invokes_uvicorn_with_parsed_args(monkeypatch) -> None:
    """`main()` should pass parsed args directly into uvicorn.run."""
    server = _import_server_with_fake_ports(monkeypatch)

    parsed = argparse.Namespace(
        host="127.0.0.1",
        port=9988,
        llm_prefix="/edge",
        no_llm=False,
        log_level="debug",
    )

    captured: dict[str, object] = {}

    monkeypatch.setattr(server, "_parse_args", lambda: parsed)

    fake_gateway_app = object()

    def fake_create_app(*, mount_llm: bool, llm_prefix: str | None, llm_app: object | None):
        captured["mount_llm"] = mount_llm
        captured["llm_prefix"] = llm_prefix
        captured["llm_app"] = llm_app
        return object()

    def fake_uvicorn_run(app, *, host: str, port: int, log_level: str) -> None:
        captured["app"] = app
        captured["host"] = host
        captured["port"] = port
        captured["log_level"] = log_level

    monkeypatch.setattr(server, "create_app", fake_create_app)
    monkeypatch.setattr(server, "_load_llm_gateway_app", lambda: fake_gateway_app)
    monkeypatch.setattr(server.uvicorn, "run", fake_uvicorn_run)

    server.main()

    assert captured["mount_llm"] is True
    assert captured["llm_prefix"] == "/edge"
    assert captured["llm_app"] is fake_gateway_app
    assert captured["host"] == "127.0.0.1"
    assert captured["port"] == 9988
    assert captured["log_level"] == "debug"


def test_server_main_no_llm_mode(monkeypatch) -> None:
    """`--no-llm` should propagate to app creation as mount_llm=False."""
    server = _import_server_with_fake_ports(monkeypatch)

    parsed = argparse.Namespace(
        host="0.0.0.0",
        port=8899,
        llm_prefix=None,
        no_llm=True,
        log_level="info",
    )

    captured: dict[str, object] = {}

    monkeypatch.setattr(server, "_parse_args", lambda: parsed)
    monkeypatch.setattr(
        server,
        "create_app",
        lambda *, mount_llm, llm_prefix, llm_app: captured.update(
            {"mount_llm": mount_llm, "llm_prefix": llm_prefix, "llm_app": llm_app}
        )
        or object(),
    )
    monkeypatch.setattr(server.uvicorn, "run", lambda *args, **kwargs: None)

    server.main()

    assert captured["mount_llm"] is False
    assert captured["llm_prefix"] is None
    assert captured["llm_app"] is None
