"""Tests for server integration — lifespan, context, and tool registration."""

from __future__ import annotations

from pathlib import Path

import pytest


class TestLifespan:
    """Test the godotiq_lifespan context manager."""

    @pytest.mark.asyncio
    async def test_lifespan_creates_session_with_project(self, monkeypatch, sample_root):
        """Lifespan yields a session when pointed at a valid Godot project."""
        monkeypatch.setenv("GODOTIQ_PROJECT_ROOT", str(sample_root))
        from godotiq.server import godotiq_lifespan, mcp

        async with godotiq_lifespan(mcp) as state:
            assert "session" in state
            assert state["session"] is not None
            assert state["session"]._index is not None

    @pytest.mark.asyncio
    async def test_lifespan_yields_none_without_project(self, monkeypatch, tmp_path):
        """Lifespan yields None session when no Godot project is found."""
        monkeypatch.delenv("GODOTIQ_PROJECT_ROOT", raising=False)
        monkeypatch.chdir(tmp_path)
        from godotiq.server import godotiq_lifespan, mcp

        async with godotiq_lifespan(mcp) as state:
            assert "session" in state
            assert state["session"] is None


class TestToolRegistration:
    """Verify tools are registered after server integration."""

    @pytest.mark.asyncio
    async def test_ping_still_registered(self):
        """godotiq_ping must still work after lifespan addition."""
        from godotiq.server import mcp

        tools = await mcp.list_tools()
        tool_names = [t.name for t in tools]
        assert "godotiq_ping" in tool_names

    def test_no_circular_imports(self):
        """Importing server should not cause circular import errors."""
        import godotiq.server  # noqa: F401
        # If we reach here, no circular import


class TestConftest:
    """Verify conftest fixtures produce valid objects."""

    def test_session_fixture_loads(self, session):
        """Session fixture should produce a loaded GodotIQSession."""
        assert session is not None
        assert session._index is not None
        assert session._index.project_name != ""

    def test_sample_root_exists(self, sample_root):
        """sample_root fixture should point to a real directory."""
        assert sample_root.exists()
        assert (sample_root / "project.godot").exists()
