"""US-001 smoke test: gateway → single stub node → valid OpenAI-format response."""

import json
import urllib.request

from meshnet_node.server import StubNodeServer
from meshnet_gateway.server import GatewayServer


def test_single_node_smoke():
    "Single node smoke\n\nTags: general"
    node = StubNodeServer()
    node_port = node.start()

    gateway = GatewayServer(node_url=f"http://127.0.0.1:{node_port}")
    gateway_port = gateway.start()

    try:
        payload = json.dumps({
            "model": "stub-model",
            "messages": [{"role": "user", "content": "hello"}],
        }).encode()

        req = urllib.request.Request(
            f"http://127.0.0.1:{gateway_port}/v1/chat/completions",
            data=payload,
            headers={"Content-Type": "application/json"},
            method="POST",
        )

        with urllib.request.urlopen(req) as resp:
            assert resp.status == 200
            assert resp.headers["Content-Type"] == "application/json"
            body = json.loads(resp.read())

        assert body["id"] == "chatcmpl-stub"
        assert body["object"] == "chat.completion"
        assert isinstance(body["created"], int)
        assert body["model"] == "stub-model"
        assert "choices" in body
        assert len(body["choices"]) == 1
        choice = body["choices"][0]
        assert choice["index"] == 0
        assert choice["message"]["role"] == "assistant"
        assert choice["message"]["content"] == "stub response to: hello"
        assert choice["finish_reason"] == "stop"
        assert body["usage"] == {
            "prompt_tokens": 0,
            "completion_tokens": 0,
            "total_tokens": 0,
        }
    finally:
        gateway.stop()
        node.stop()
