from __future__ import annotations

import importlib.util
from pathlib import Path
from typing import Any


SERVER_PATH = Path(__file__).resolve().parents[1] / "server.py"


def _load_server_module():
    spec = importlib.util.spec_from_file_location("deploy_control_server_connector_tests", SERVER_PATH)
    assert spec and spec.loader
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def test_new_instance_receives_external_connector_configuration(monkeypatch) -> None:
    server = _load_server_module()
    commands: list[list[str]] = []
    record: dict[str, Any] = {
        "instance_id": "terminaltest",
        "container_name": "app-instance-terminaltest",
        "host_port": 20001,
        "public_url": "http://terminaltest.example.test",
    }
    lookups = iter([None, None, record])

    monkeypatch.setattr(server, "get_registry_record", lambda **_kwargs: next(lookups))
    monkeypatch.setattr(server, "ensure_network", lambda: None)
    monkeypatch.setattr(server, "ensure_proxy", lambda: None)
    monkeypatch.setattr(server, "wait_for_backend", lambda _record: None)
    monkeypatch.setattr(server, "DEFAULT_EXTERNAL_CONNECTOR_BASE_URL", "http://external-connector:8787")
    monkeypatch.setattr(server, "DEFAULT_EXTERNAL_CONNECTOR_TOKEN", "connector-token")
    monkeypatch.setattr(server, "DEFAULT_BEAVER_BRIDGE_TOKEN", "bridge-token")
    monkeypatch.setattr(server, "DEFAULT_INITIAL_SKILLS_DIR", "/srv/beaver/skills")
    monkeypatch.setattr(server, "DEFAULT_AUTHZ_OUTLOOK_MCP_URL", "http://bw-outlook-mcp:8000/mcp")
    monkeypatch.setattr(server, "DEFAULT_OUTLOOK_MCP_CALL_TIMEOUT_SECONDS", "60")

    def capture_command(args: list[str], **_kwargs: Any) -> str:
        commands.append(args)
        return ""

    monkeypatch.setattr(server, "run_command", capture_command)

    result = server.create_or_get_instance(
        {
            "username": "terminaltest",
            "password": "secret",
            "instance_id": "terminaltest",
        }
    )

    command = commands[0]
    assert command[command.index("--external-connector-base-url") + 1] == "http://external-connector:8787"
    assert command[command.index("--external-connector-token") + 1] == "connector-token"
    assert command[command.index("--bridge-token") + 1] == "bridge-token"
    assert command[command.index("--initial-skills-dir") + 1] == "/srv/beaver/skills"
    assert command[command.index("--outlook-mcp-call-timeout-seconds") + 1] == "60"
    assert result["created"] is True
