import importlib.util
import os
import pathlib
import tempfile
import unittest
from unittest import mock


class UpdateLockBoundaryTest(unittest.TestCase):
    @staticmethod
    def load_update_lock_module():
        repo = pathlib.Path(__file__).resolve().parents[1]
        update_lock = repo / "scripts" / "update-lock.py"
        spec = importlib.util.spec_from_file_location("update_lock", update_lock)
        assert spec and spec.loader
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        return module

    def test_update_lock_skips_system_tools(self):
        update_lock = self.load_update_lock_module()

        with tempfile.TemporaryDirectory() as tmp:
            tmp_path = pathlib.Path(tmp)
            bin_dir = tmp_path / "bin"
            bin_dir.mkdir()

            for name, version in {"git": "git version 2.50.1", "nvim": "NVIM v0.12.2"}.items():
                cmd = bin_dir / name
                cmd.write_text(f"#!/usr/bin/env bash\necho '{version}'\n", encoding="utf-8")
                cmd.chmod(0o755)

            manifest = tmp_path / "deps.toml"
            manifest.write_text(
                """
[deps.git]
command = "git"
target = "latest"

[deps.git.linux]
installer = "system"
source = "https://git-scm.com/downloads"

[deps.nvim]
command = "nvim"
target = "v0.12.2"

[deps.nvim.linux]
installer = "official_tarball"
source = "https://neovim.io/doc/install/"
""".strip(),
                encoding="utf-8",
            )

            lock = tmp_path / "deps.lock"

            env = os.environ.copy()
            env["PATH"] = f"{bin_dir}:{env['PATH']}"

            with mock.patch.dict(os.environ, env, clear=False):
                with mock.patch.object(update_lock, "current_arch", return_value="arm64"):
                    with mock.patch.object(update_lock, "checksum_for_source", return_value="deadbeef"):
                        with mock.patch("sys.argv", [
                            "update-lock.py",
                            str(manifest),
                            str(lock),
                            "--platform",
                            "linux",
                            "--manifest-commit",
                            "test",
                        ]):
                            update_lock.main()

            text = lock.read_text(encoding="utf-8")
            self.assertIn("[deps.nvim.linux.arm64]", text)
            self.assertNotIn("[deps.git", text)


if __name__ == "__main__":
    unittest.main()
