"""pytest plugin for mcp-forge.

Auto-registered via entry_points in pyproject.toml.
Provides fixtures and CLI options for MCP server testing.
"""

from __future__ import annotations

from pathlib import Path

import pytest

from mcp_forge.client import MCPTestClient
from mcp_forge.snapshot import SnapshotManager


def pytest_addoption(parser: pytest.Parser) -> None:
    """Add mcp-forge CLI options to pytest."""
    group = parser.getgroup("mcp-forge", "MCP server testing")
    group.addoption(
        "--update-snapshots",
        action="store_true",
        default=False,
        help="Update mcp-forge snapshot files instead of comparing against them.",
    )
    group.addoption(
        "--mcp-timeout",
        type=float,
        default=10.0,
        help="Default timeout for MCP server connections (seconds).",
    )


@pytest.fixture
def forge_snapshot(request: pytest.FixtureRequest) -> SnapshotManager:
    """Provide a SnapshotManager configured for the current test.

    Usage:
        async def test_something(client, forge_snapshot):
            result = await client.call_tool("my_tool", {"x": 1})
            forge_snapshot.assert_match(result)
    """
    update = request.config.getoption("--update-snapshots", default=False)
    test_file = Path(str(request.fspath))
    test_name = request.node.name
    snap_dir = test_file.parent / "__snapshots__"

    return SnapshotManager(
        snap_dir=snap_dir,
        test_name=test_name,
        update=update,
    )


@pytest.fixture
def forge_server(request: pytest.FixtureRequest):
    """Factory fixture for creating MCPTestClient instances.

    Usage:
        async def test_something(forge_server):
            async with forge_server("python my_server.py") as client:
                tools = await client.list_tools()
                assert len(tools) > 0
    """
    timeout = request.config.getoption("--mcp-timeout", default=10.0)

    def _factory(
        command: str,
        *,
        env: dict[str, str] | None = None,
        cwd: str | None = None,
    ) -> MCPTestClient:
        return MCPTestClient.from_command(
            command, env=env, cwd=cwd, timeout=timeout
        )

    return _factory


@pytest.fixture
def mcp_timeout(request: pytest.FixtureRequest) -> float:
    """Get the configured MCP timeout value."""
    return request.config.getoption("--mcp-timeout", default=10.0)
