"""Tests for AppContext.local_project_dir guarding against cross-project path corruption."""

from __future__ import annotations

from unittest.mock import MagicMock

from loom.mcp.server import AppContext


def _make_ctx(project_id: str = "proj-1", home_project_id: str = "proj-1", project_dir: str = "/code/loom") -> AppContext:
    return AppContext(
        pool=MagicMock(),
        redis=MagicMock(),
        project_id=project_id,
        project_dir=project_dir,
        _home_project_id=home_project_id,
    )


class TestLocalProjectDir:
    def test_same_project_returns_dir(self):
        ctx = _make_ctx(project_id="proj-1", home_project_id="proj-1")
        assert ctx.local_project_dir == "/code/loom"

    def test_different_project_returns_none(self):
        ctx = _make_ctx(project_id="proj-2", home_project_id="proj-1")
        assert ctx.local_project_dir is None

    def test_switch_back_restores_dir(self):
        ctx = _make_ctx(project_id="proj-1", home_project_id="proj-1")
        assert ctx.local_project_dir == "/code/loom"
        ctx.project_id = "proj-2"
        assert ctx.local_project_dir is None
        ctx.project_id = "proj-1"
        assert ctx.local_project_dir == "/code/loom"

    def test_empty_project_dir_returns_none(self):
        ctx = _make_ctx(project_dir="")
        assert ctx.local_project_dir is None

    def test_no_home_project_id_returns_dir(self):
        """When _home_project_id is empty (e.g. no config), still returns project_dir."""
        ctx = _make_ctx(home_project_id="")
        assert ctx.local_project_dir == "/code/loom"
