"""Tests for dynamic __version__ and version propagation to godotiq_ping."""

import json
import re

import pytest


class TestVersionAttribute:
    """Verify __version__ is accessible, correct type, and plausible format."""

    def test_version_is_importable_from_top_level(self):
        """__version__ can be imported directly from godotiq."""
        from godotiq import __version__
        assert __version__ is not None

    def test_version_is_a_string(self):
        """__version__ must be a str."""
        from godotiq import __version__
        assert isinstance(__version__, str)

    def test_version_matches_expected(self):
        """__version__ should equal the version in pyproject.toml (currently 0.1.0)."""
        from godotiq import __version__
        assert __version__ == "0.1.1"

    def test_version_looks_like_semver_or_dev(self):
        """__version__ should be a semver string or the dev fallback."""
        from godotiq import __version__
        assert re.match(r"^\d+\.\d+\.\d+", __version__) or __version__ == "0.0.0-dev"

    def test_version_fallback_when_package_not_found(self, monkeypatch):
        """_get_version returns '0.0.0-dev' when package metadata is unavailable."""
        from importlib.metadata import PackageNotFoundError
        import godotiq

        monkeypatch.setattr(
            "godotiq.version",
            lambda name: (_ for _ in ()).throw(PackageNotFoundError(name)),
        )
        assert godotiq._get_version() == "0.0.0-dev"


class TestPingUsesDynamicVersion:
    """Verify godotiq_ping returns __version__ rather than a hardcoded string."""

    @pytest.mark.asyncio
    async def test_ping_version_matches_package_version(self):
        """The version in godotiq_ping response must equal godotiq.__version__."""
        from godotiq import __version__
        from godotiq.server import mcp

        result = await mcp.call_tool("godotiq_ping", {})
        payload = json.loads(result[0].text)
        assert payload["version"] == __version__

    @pytest.mark.asyncio
    async def test_ping_version_key_exists(self):
        """godotiq_ping response must include a 'version' key."""
        from godotiq.server import mcp

        result = await mcp.call_tool("godotiq_ping", {})
        payload = json.loads(result[0].text)
        assert "version" in payload
