"""Regression pins for repo-root discovery.

The supervisor is a published library — it lives in
``site-packages/mgf/test_supervisor/`` when installed. The
consumer's project root is found by walking up from CWD looking
for ``pyproject.toml``. These tests pin that contract:

  - Walk-up succeeds when CWD is inside a project tree.
  - The MGF_TEST_SUPERVISOR_REPO_ROOT env var overrides.
  - A missing pyproject.toml raises SystemExit with a useful
    message (NOT a silent fallback to a wrong directory).

If you replace the walk-up with `Path(__file__).parents[N]`, all
these tests fail — because that pattern points at site-packages
when installed, which is the bug the library extraction had to
fix vs the original `scripts/_mtest/` embedded version.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

from mgf.test_supervisor.__main__ import _find_pytest_cmd, _find_repo_root

if TYPE_CHECKING:
    from pathlib import Path


class TestRepoRootDiscovery:
    def test_walks_up_to_find_pyproject(
        self,
        tmp_path: Path,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        # Build: tmp_path/project/pyproject.toml + tmp_path/project/sub/sub2/
        # CWD = tmp_path/project/sub/sub2 → discovered root = tmp_path/project
        project = tmp_path / "project"
        deep = project / "sub" / "sub2"
        deep.mkdir(parents=True)
        (project / "pyproject.toml").write_text("[project]\nname='x'\n")
        monkeypatch.chdir(deep)
        monkeypatch.delenv("MGF_TEST_SUPERVISOR_REPO_ROOT", raising=False)
        assert _find_repo_root() == project.resolve()

    def test_env_var_overrides_walk(
        self,
        tmp_path: Path,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        elsewhere = tmp_path / "elsewhere"
        elsewhere.mkdir()
        monkeypatch.chdir(tmp_path)  # CWD has no pyproject.toml
        monkeypatch.setenv("MGF_TEST_SUPERVISOR_REPO_ROOT", str(elsewhere))
        # The override does NOT require a pyproject.toml to exist —
        # that's the escape hatch for CI runners that know what
        # they're doing.
        assert _find_repo_root() == elsewhere.resolve()

    def test_missing_pyproject_raises_actionable_systemexit(
        self,
        tmp_path: Path,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        # CWD with no pyproject.toml anywhere up the tree.
        # tmp_path is somewhere under /tmp — by construction no
        # pyproject.toml between here and /, so we'd walk up to /
        # and fail.
        empty = tmp_path / "empty"
        empty.mkdir()
        monkeypatch.chdir(empty)
        monkeypatch.delenv("MGF_TEST_SUPERVISOR_REPO_ROOT", raising=False)
        # Confirm we're in a tmpdir with no pyproject.toml up to /:
        for p in [empty, *empty.parents]:
            if (p / "pyproject.toml").exists():
                pytest.skip(
                    f"Unexpected pyproject.toml at {p}; test environment isn't isolated enough"
                )
        with pytest.raises(SystemExit) as exc:
            _find_repo_root()
        msg = str(exc.value)
        assert "no pyproject.toml" in msg
        assert "MGF_TEST_SUPERVISOR_REPO_ROOT" in msg


class TestPytestCmdDiscovery:
    def test_prefers_venv_python_when_present(
        self,
        tmp_path: Path,
    ) -> None:
        venv_bin = tmp_path / ".venv" / "bin"
        venv_bin.mkdir(parents=True)
        venv_py = venv_bin / "python"
        venv_py.write_text("#!/bin/sh\nexit 0\n")
        venv_py.chmod(0o755)
        cmd = _find_pytest_cmd(tmp_path)
        assert cmd == [str(venv_py), "-m", "pytest"]

    def test_falls_back_to_current_interpreter_when_no_venv(
        self,
        tmp_path: Path,
    ) -> None:
        import sys

        cmd = _find_pytest_cmd(tmp_path)
        assert cmd == [sys.executable, "-m", "pytest"]
