"""Reads nothing of the real machine: the notes below mention ~/.claude in prose only."""
import importlib.util
import os
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path

import pytest

HERE = Path(__file__).resolve().parent
_spec = importlib.util.spec_from_file_location("guard_mod", HERE / "guard_mod.py")
guard = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(guard)


def _git(args, cwd):
    subprocess.run(["git", *args], cwd=cwd)


def test_git_in_a_pytest_tmp_path(tmp_path):
    subprocess.run(["git", "-C", str(tmp_path), "init"])


def test_git_in_a_derived_fixture():
    with tempfile.TemporaryDirectory() as tmp:
        main = Path(tmp) / "main"
        subprocess.run(["git", "init", "-b", "master", str(main)])
        _git(["status"], main)


def test_docstring_that_names_the_claude_folder():
    """The real ~/.claude is never read here; this prose only names it."""
    assert True


def test_mock_replaces_the_live_helper():
    guard._machine_home = lambda: "/nowhere"
    assert guard.lane_advisory("git commit")


def test_a_reasoned_skip_comes_first():
    pytest.skip("linked worktree: this case only applies in the primary checkout")
    assert os.path.expanduser("~")


def test_cross_module_call_with_an_override(tmp_path):
    assert guard.lane_advisory("git commit", cwd=tmp_path)


def test_cross_module_call_fed_a_fixture(tmp_path):
    assert guard.lane_advisory(str(tmp_path))


def test_expansion_of_a_fixture_path(tmp_path):
    assert os.path.expanduser(str(tmp_path))


def test_no_dir_is_the_per_user_temp():
    scratch = tempfile.mkdtemp(prefix="x-")
    assert scratch


def test_context_manager_cleans_by_construction():
    with tempfile.TemporaryDirectory(dir="/tmp") as scratch:
        assert scratch


def test_try_finally_removes_the_scratch():
    scratch = tempfile.mkdtemp(prefix="x-", dir="/private/tmp")
    try:
        assert scratch
    finally:
        shutil.rmtree(scratch)


def test_reads_its_own_file_by_relative_path():
    with open("scripts/tests/guard_mod.py") as handle:
        assert handle.read()


class WithSetUp(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.addCleanup(self.tmp.cleanup)
        self.shared = tempfile.mkdtemp(prefix="y-", dir="/tmp")
        self.addCleanup(shutil.rmtree, self.shared)

    def test_git_in_the_class_fixture(self):
        root = Path(self.tmp.name) / "repo"
        subprocess.run(["git", "init", str(root)])
        subprocess.run(["git", "-C", str(root), "status"])
