"""Tests for specter_cli.proxy — remote execution proxy."""

from __future__ import annotations

from specter_cli.proxy import _build_env_forwards, _compute_remote_cwd


class TestComputeRemoteCwd:
    def test_same_as_root(self, tmp_path):
        result = _compute_remote_cwd(tmp_path, tmp_path, "~/.specter/workspace")
        assert result == "~/.specter/workspace"

    def test_subdirectory(self, tmp_path):
        sub = tmp_path / "src" / "pkg"
        sub.mkdir(parents=True)
        result = _compute_remote_cwd(tmp_path, sub, "~/.specter/workspace")
        assert result == "~/.specter/workspace/src/pkg"

    def test_outside_root(self, tmp_path):
        other = tmp_path / "other"
        other.mkdir()
        root = tmp_path / "project"
        root.mkdir()
        result = _compute_remote_cwd(root, other, "~/.specter/workspace")
        assert result == "~/.specter/workspace"

    def test_custom_workspace(self, tmp_path):
        sub = tmp_path / "tests"
        sub.mkdir()
        result = _compute_remote_cwd(tmp_path, sub, "/opt/specter/work")
        assert result == "/opt/specter/work/tests"

    def test_deep_nesting(self, tmp_path):
        deep = tmp_path / "a" / "b" / "c" / "d"
        deep.mkdir(parents=True)
        result = _compute_remote_cwd(tmp_path, deep, "~/.specter/workspace")
        assert result == "~/.specter/workspace/a/b/c/d"


class TestBuildEnvForwards:
    def test_no_env_vars_set(self, monkeypatch):
        for var in [
            "CUDA_VISIBLE_DEVICES",
            "TORCH_DTYPE",
            "PYTHONPATH",
            "PYTHONDONTWRITEBYTECODE",
            "PYTHONUNBUFFERED",
        ]:
            monkeypatch.delenv(var, raising=False)
        result = _build_env_forwards({})
        assert result == []

    def test_cuda_visible_devices(self, monkeypatch):
        monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0,1")
        result = _build_env_forwards({})
        assert any("CUDA_VISIBLE_DEVICES" in r for r in result)
        assert any("0,1" in r for r in result)

    def test_multiple_vars(self, monkeypatch):
        monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0")
        monkeypatch.setenv("PYTHONUNBUFFERED", "1")
        result = _build_env_forwards({})
        assert len(result) == 2

    def test_quoting_special_chars(self, monkeypatch):
        monkeypatch.setenv("PYTHONPATH", "/path with spaces:/other")
        result = _build_env_forwards({})
        assert len(result) == 1
        # shlex.quote should handle the spaces.
        assert "PYTHONPATH" in result[0]
