"""Issue #2 regression tests: orchestration/implementation boundary."""

from __future__ import annotations

import importlib
import sys
import types

import pytest
from fastapi import FastAPI


def _import_server_module(monkeypatch: pytest.MonkeyPatch):
    """Import `sage.edge.server` with minimal `sage.common` stubs."""
    ports_module = types.ModuleType("sage.common.config.ports")

    class _Ports:
        EDGE_DEFAULT = 8899

    ports_module.SagePorts = _Ports

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


def test_server_loader_fetches_gateway_app_from_module(monkeypatch: pytest.MonkeyPatch) -> None:
    """Server module should load gateway app from gateway module boundary."""
    server_module = _import_server_module(monkeypatch)
    expected_app = FastAPI(title="Injected Gateway")
    gateway_module = types.ModuleType("sage.llm.gateway.server")
    gateway_module.app = expected_app
    monkeypatch.setitem(sys.modules, "sage.llm.gateway.server", gateway_module)

    loaded_app = server_module._load_llm_gateway_app()
    assert loaded_app is expected_app


def test_server_loader_fail_fast_when_gateway_missing(monkeypatch: pytest.MonkeyPatch) -> None:
    """Gateway import should fail fast when module is unavailable."""
    server_module = _import_server_module(monkeypatch)
    monkeypatch.delitem(sys.modules, "sage.llm.gateway.server", raising=False)

    original_import = __import__

    def fake_import(name, globals=None, locals=None, fromlist=(), level=0):  # type: ignore[no-untyped-def]
        if name == "sage.llm.gateway.server":
            raise ImportError("gateway not installed")
        return original_import(name, globals, locals, fromlist, level)

    monkeypatch.setattr("builtins.__import__", fake_import)

    with pytest.raises(ImportError, match="gateway not installed"):
        server_module._load_llm_gateway_app()
