"""Unit tests for the GodotIQ MCP server — Sprint 0."""

import json

import pytest

from godotiq.server import mcp, main
from godotiq.parsers.tscn_parser import parse_tscn
from godotiq.parsers.gd_parser import parse_gd
from godotiq.parsers.tres_parser import parse_tres
from godotiq.config import load_config


class TestServerInstance:
    """AC-3: Server object exists and is a FastMCP instance."""

    def test_server_instance_created(self) -> None:
        from mcp.server.fastmcp import FastMCP

        assert isinstance(mcp, FastMCP)


class TestPingTool:
    """AC-3: godotiq_ping tool is registered and returns expected response."""

    @pytest.mark.asyncio
    async def test_ping_tool_registered(self) -> None:
        tools = await mcp.list_tools()
        tool_names = [t.name for t in tools]
        assert "godotiq_ping" in tool_names

    @pytest.mark.asyncio
    async def test_ping_returns_expected(self) -> None:
        # Reset update check cache so the test is deterministic
        import godotiq.server as _srv
        _srv._update_checked = False
        _srv._cached_update_version = None
        # Mock the PyPI check to avoid network calls
        from unittest.mock import AsyncMock, patch
        with patch.object(_srv, "_check_pypi_update", new_callable=AsyncMock, return_value=None):
            result = await mcp.call_tool("godotiq_ping", {})
        payload = json.loads(result[0].text)
        from godotiq import __version__
        assert payload == {"status": "ok", "version": __version__, "license": "community"}


class TestParserStubs:
    """AC-4: Parser placeholders and implemented parsers behave correctly."""

    def test_parse_tscn_raises_file_not_found_for_bad_path(self) -> None:
        """parse_tscn is implemented and raises FileNotFoundError for nonexistent path."""
        with pytest.raises(FileNotFoundError):
            parse_tscn("/nonexistent/path/scene.tscn")

    def test_parse_gd_missing_file_raises(self) -> None:
        with pytest.raises(FileNotFoundError):
            parse_gd("/nonexistent/path.gd")

    def test_parse_tres_stub_raises(self) -> None:
        with pytest.raises(NotImplementedError):
            parse_tres("")


class TestConfig:
    """AC-6: Configuration loader returns defaults and reads JSON."""

    def test_config_defaults(self) -> None:
        config = load_config("/nonexistent/path/.godotiq.json")
        assert config.project["engine"] == "godot_4"
        assert config.conventions == {}
        assert config.token_optimization["enable_diff_cache"] is True

    def test_config_loads_json(self, tmp_config) -> None:
        config = load_config(str(tmp_config))
        assert config.project["name"] == "Test Project"
        assert config.conventions["naming"] == "snake_case"
        assert config.token_optimization["default_detail"] == "compact"
