import pytest
from pathlib import Path
from src import mcp_client
from src.result_types import Result, ErrorKind, ErrorInfo, NilPath


@pytest.fixture(autouse=True)
def _allow_tmp_path(tmp_path: Path):
 original_bases = list(mcp_client._base_dirs)
 original_primary = mcp_client._primary_base_dir
 mcp_client.configure([{"path": str(tmp_path)}], [str(tmp_path)])
 yield
 mcp_client.configure([{"path": str(b)} for b in original_bases], None)
 mcp_client._primary_base_dir = original_primary


def test_resolve_and_check_result_returns_result_type(tmp_path: Path) -> None:
 r = mcp_client._resolve_and_check_result(str(tmp_path))
 assert isinstance(r, Result)
 assert hasattr(r, "data")
 assert hasattr(r, "errors")
 assert hasattr(r, "ok")
 assert r.ok is True
 assert isinstance(r.data, Path)


def test_resolve_and_check_result_invalid_path_returns_nil_with_error() -> None:
 r = mcp_client._resolve_and_check_result("\x00invalid\x00path\x00")
 assert r.ok is False
 assert isinstance(r.data, NilPath)
 assert len(r.errors) >= 1
 assert r.errors[0].kind in (ErrorKind.INVALID_INPUT, ErrorKind.PERMISSION)


def test_read_file_result_returns_result_str(tmp_path: Path) -> None:
 r = mcp_client.read_file_result(str(tmp_path))
 assert isinstance(r, Result)
 assert hasattr(r, "data")
 assert r.data == ""
 assert r.ok is False
 assert len(r.errors) >= 1
 assert r.errors[0].kind in (ErrorKind.NOT_FOUND, ErrorKind.PERMISSION, ErrorKind.INVALID_INPUT)


def test_read_file_result_reads_existing_file(tmp_path: Path) -> None:
 f = tmp_path / "test.txt"
 f.write_text("hello world", encoding="utf-8")
 r = mcp_client.read_file_result(str(f))
 assert r.ok is True
 assert r.data == "hello world"
 assert r.errors == []


def test_list_directory_result_returns_result_str(tmp_path: Path) -> None:
 r = mcp_client.list_directory_result(str(tmp_path))
 assert isinstance(r, Result)
 assert r.ok is True
 assert "Directory:" in r.data


def test_search_files_result_returns_result_str(tmp_path: Path) -> None:
 f = tmp_path / "test.py"
 f.write_text("# test", encoding="utf-8")
 r = mcp_client.search_files_result(str(tmp_path), "*.py")
 assert isinstance(r, Result)
 assert r.ok is True
 assert "test.py" in r.data
