import hashlib
import os
import pathlib
import stat
import subprocess
import tarfile
import tempfile
import unittest


class InstallDepsPinnedSourceTest(unittest.TestCase):
    def make_executable(self, path: pathlib.Path, content: str) -> None:
        path.write_text(content, encoding="utf-8")
        path.chmod(path.stat().st_mode | stat.S_IEXEC)

    def test_install_uses_pinned_source_url_from_lock(self):
        repo = pathlib.Path(__file__).resolve().parents[1]
        script = repo / "scripts" / "install-deps"

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

            fake_artifact = tmp_path / "eza.tar.gz"
            import io
            with tarfile.open(fake_artifact, "w:gz") as tar:
                data = b"#!/usr/bin/env bash\necho 'eza 0.23.4'\n"
                info = tarfile.TarInfo("eza")
                info.mode = 0o755
                info.size = len(data)
                tar.addfile(info, io.BytesIO(data))

            checksum = hashlib.sha256(fake_artifact.read_bytes()).hexdigest()
            pinned_url = "https://github.com/eza-community/eza/releases/download/v0.23.4/eza_x86_64-unknown-linux-gnu.tar.gz"
            latest_api_url = "https://api.github.com/repos/eza-community/eza/releases/latest"
            log_path = tmp_path / "curl.log"

            self.make_executable(
                bin_dir / "uname",
                "#!/usr/bin/env bash\ncase \"$1\" in\n  -s) printf 'Linux\\n' ;;\n  -m) printf 'x86_64\\n' ;;\n  *) printf 'Linux\\n' ;;\nesac\n",
            )

            self.make_executable(
                bin_dir / "curl",
                f"""#!/usr/bin/env bash
set -eu
log_file="${{URL_LOG:?}}"
artifact="${{FAKE_ARTIFACT:?}}"
url=""
out=""
while [ "$#" -gt 0 ]; do
  case "$1" in
    -o)
      shift
      out="$1"
      ;;
    -*)
      ;;
    *)
      url="$1"
      ;;
  esac
  shift
done
printf '%s\\n' "$url" >> "$log_file"
if [ -n "$out" ]; then
  cp "$artifact" "$out"
else
  printf '{{"tag_name":"v9.9.9"}}'
fi
""",
            )

            home = tmp_path / "home"
            home.mkdir()

            manifest = tmp_path / "deps.toml"
            manifest.write_text(
                """
[deps.eza]
command = "eza"
target = "v0.23.4"

[deps.eza.linux]
installer = "official_release"
source = "https://github.com/eza-community/eza/blob/main/INSTALL.md"
""".strip(),
                encoding="utf-8",
            )

            lock = tmp_path / "deps.lock"
            lock.write_text(
                f"""
[meta]
generated_at = "2026-05-10T00:00:00Z"
generator_version = "1"
manifest_commit = "test"

[deps.eza]
target = "v0.23.4"

[deps.eza.linux.x86_64]
platform = "linux"
arch = "x86_64"
installer = "official_release"
version = "eza 0.23.4"
source_url = "{pinned_url}"
checksum = "{checksum}"
filename = "eza_x86_64-unknown-linux-gnu.tar.gz"
""".strip()
                + "\n",
                encoding="utf-8",
            )

            env = os.environ.copy()
            env["PATH"] = f"{bin_dir}:{env['PATH']}"
            env["HOME"] = str(home)
            env["DEPS_FILE"] = str(manifest)
            env["LOCK_FILE"] = str(lock)
            env["URL_LOG"] = str(log_path)
            env["FAKE_ARTIFACT"] = str(fake_artifact)

            result = subprocess.run(
                [str(script), "install", "--only", "eza"],
                env=env,
                capture_output=True,
                text=True,
                check=False,
            )

            self.assertEqual(result.returncode, 0, msg=result.stdout + result.stderr)
            urls = log_path.read_text(encoding="utf-8").splitlines()
            self.assertIn(pinned_url, urls)
            self.assertNotIn(latest_api_url, urls)


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