import os
import tempfile

import pytest

from my_mcp.path_validator import (
    PathNotAllowedError,
    is_path_allowed,
    resolve_path,
    validate_path,
)


class TestResolvePath:
    def test_resolves_relative_path(self):
        result = resolve_path("some/relative/path")
        assert result.is_absolute()

    def test_resolves_absolute_path(self):
        result = resolve_path("/tmp/test")
        assert result.is_absolute()


class TestIsPathAllowed:
    def test_path_in_allowed_dir(self):
        with tempfile.TemporaryDirectory() as tmp:
            assert is_path_allowed(os.path.join(tmp, "file.txt"), [tmp])

    def test_path_in_subdir(self):
        with tempfile.TemporaryDirectory() as tmp:
            subdir = os.path.join(tmp, "subdir", "nested")
            os.makedirs(subdir)
            assert is_path_allowed(os.path.join(subdir, "file.txt"), [tmp])

    def test_path_outside_allowed_dir(self):
        with tempfile.TemporaryDirectory() as tmp:
            assert not is_path_allowed("/etc/passwd", [tmp])

    def test_path_traversal_blocked(self):
        with tempfile.TemporaryDirectory() as tmp:
            traversal = os.path.join(tmp, "..", "..", "etc", "passwd")
            assert not is_path_allowed(traversal, [tmp])

    def test_empty_allowed_dirs(self):
        assert not is_path_allowed("/any/path", [])

    def test_multiple_allowed_dirs(self):
        with tempfile.TemporaryDirectory() as tmp1:
            with tempfile.TemporaryDirectory() as tmp2:
                assert is_path_allowed(os.path.join(tmp1, "file.txt"), [tmp1, tmp2])
                assert is_path_allowed(os.path.join(tmp2, "file.txt"), [tmp1, tmp2])
                assert not is_path_allowed("/etc/passwd", [tmp1, tmp2])


class TestValidatePath:
    def test_returns_resolved_path(self):
        with tempfile.TemporaryDirectory() as tmp:
            result = validate_path(os.path.join(tmp, "file.txt"), [tmp])
            assert result.is_absolute()

    def test_raises_for_forbidden_path(self):
        with tempfile.TemporaryDirectory() as tmp:
            with pytest.raises(PathNotAllowedError) as exc_info:
                validate_path("/etc/passwd", [tmp])
            assert "/etc/passwd" in str(exc_info.value)
            # On Windows, list repr double-escapes backslashes
            error_msg = str(exc_info.value)
            assert tmp in error_msg or tmp.replace("\\", "\\\\") in error_msg
