"""{{ display_name }} MCP server — generated by mcpify. Do not hand-edit.

Builds the real `FastMCP` server (`core.mcp_server.build_server`) and
calls its tools directly — the one test in this suite that pays
`sentence-transformers`' real model-load cost, since it exercises the
actual embedding path `services.populate_embeddings` and the `search`
tool both go through.
"""

from __future__ import annotations

import json
import sqlite3
from pathlib import Path

import pytest
import sqlite_vec

from {{ module_name }}.auth.auth_manager import AuthManager
from {{ module_name }}.core.config import AuthMethod, Config
from {{ module_name }}.core.mcp_server import build_server
from {{ module_name }}.data.store import close_cached_connections
from {{ module_name }}.services.embedding_service import embed
from {{ module_name }}.services.populate_embeddings import populate


@pytest.fixture
def real_embeddings_db_path(tmp_path: Path) -> Path:
    db_path = tmp_path / "mcp_store.db"
    conn = sqlite3.connect(db_path)
    conn.enable_load_extension(True)
    sqlite_vec.load(conn)
    conn.enable_load_extension(False)
    dim = len(embed("warm-up"))

    conn.execute(
        "CREATE TABLE endpoints ("
        "operation_id TEXT PRIMARY KEY, path TEXT NOT NULL, method TEXT NOT NULL, "
        "summary TEXT, description TEXT, input_schema TEXT NOT NULL, "
        "output_schema TEXT NOT NULL, auth_scheme_ref TEXT)"
    )
    conn.execute(
        f"CREATE VIRTUAL TABLE semantic_endpoints USING vec0("
        f"operation_id TEXT PRIMARY KEY, embedding FLOAT[{dim}])"
    )
    conn.execute(
        "INSERT INTO endpoints VALUES "
        "('listWidgets', '/widgets', 'GET', 'List widgets', 'Lists all widgets', '{}', '[]', NULL)"
    )
    conn.commit()
    conn.close()
    return db_path


async def test_search_and_get_tools_respond_with_real_embeddings(
    real_embeddings_db_path: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    await populate(real_embeddings_db_path)

    # `build_server` now resolves its store via `api_version` ->
    # `resolve_store_path`, which is relative-to-cwd (matching how the
    # real binary always runs next to its own `mcp_store.db`) — chdir into
    # the fixture's directory so that resolution lands on
    # `real_embeddings_db_path` instead of the real project's own store.
    monkeypatch.chdir(real_embeddings_db_path.parent)

    config = Config(
        url="https://api.example.com",
        auth_method=AuthMethod.{% if auth_methods | length > 0 %}{{ auth_methods.0.class_name | upper }}{% else %}NONE{% endif %},
    )
    auth_manager = AuthManager(config.auth_method)
    mcp = build_server(config.api_version, config, auth_manager)

    try:
        tools = await mcp.list_tools()
        assert {tool.name for tool in tools} == {"search", "get", "call"}

        search_result = await mcp.call_tool("search", {"query": "list all widgets", "limit": 5})
        search_content = (
            search_result[0][0] if isinstance(search_result, tuple) else search_result.content[0]
        )
        search_parsed = json.loads(search_content.text)
        assert search_parsed[0]["operation_id"] == "listWidgets"

        get_result = await mcp.call_tool("get", {"operation_id": "listWidgets"})
        get_content = get_result[0][0] if isinstance(get_result, tuple) else get_result.content[0]
        get_parsed = json.loads(get_content.text)
        assert get_parsed["path"] == "/widgets"
    finally:
        # `mcp`'s tool calls went through `cached_store_connection`, which
        # (unlike `open_store`) is deliberately never closed by its
        # callers — see `close_cached_connections`'s docstring for why
        # this test must close it explicitly.
        await close_cached_connections()
