"""Wspólne fixtures pytest — uruchamia testowe serwery MCP."""

import threading
import time

import pytest
import uvicorn

from .test_server import create_app
from .test_server_b import create_app as create_app_b

TEST_HOST = "127.0.0.1"
TEST_PORT = 18123
TEST_URL = f"http://{TEST_HOST}:{TEST_PORT}/mcp/"

TEST_B_HOST = "127.0.0.1"
TEST_B_PORT = 18133
TEST_B_URL = f"http://{TEST_B_HOST}:{TEST_B_PORT}/mcp/"


def _start_uvicorn(app, host, port):
    config = uvicorn.Config(app, host=host, port=port, log_level="warning")
    server = uvicorn.Server(config)
    thread = threading.Thread(target=server.run, daemon=True)
    thread.start()

    deadline = time.time() + 5
    import httpx
    while time.time() < deadline:
        try:
            httpx.get(f"http://{host}:{port}/")
            break
        except Exception:
            time.sleep(0.1)

    return server


@pytest.fixture(scope="session")
def mcp_server_url():
    """Uruchamia testowy serwer MCP (z resources) raz na całą sesję testową."""
    server = _start_uvicorn(create_app(), TEST_HOST, TEST_PORT)
    yield TEST_URL
    server.should_exit = True


@pytest.fixture(scope="session")
def mcp_server_b_url():
    """Drugi testowy serwer MCP — bez resources, inne narzędzia."""
    server = _start_uvicorn(create_app_b(), TEST_B_HOST, TEST_B_PORT)
    yield TEST_B_URL
    server.should_exit = True
