#!/usr/bin/env python3

import tempfile
import unittest
from pathlib import Path

import update_llvm_distributions


class UpdateLlvmDistributionsTest(unittest.TestCase):
    def release(self, *, missing_digest: bool = False) -> dict:
        assets = []
        for index, platform in enumerate(
            update_llvm_distributions.LLVM_DISTRIBUTION_PLATFORMS, start=1
        ):
            asset = {
                "name": f"LLVM-22.1.8-{platform}.tar.xz",
                "digest": f"sha256:{index:064x}",
            }
            assets.append(asset)
        if missing_digest:
            assets[0]["digest"] = None
        return {"tag_name": "llvmorg-22.1.8", "assets": assets}

    def test_updates_asset_versions_and_digests(self) -> None:
        with tempfile.TemporaryDirectory() as directory:
            module = Path(directory) / "MODULE.bazel"
            module.write_text(
                'LLVM_VERSION = "22.1.8"\n\n'
                "LLVM_DISTRIBUTIONS = {\n"
                '    "LLVM-22.1.7-Linux-ARM64.tar.xz": "old-arm",\n'
                '    "LLVM-22.1.7-Linux-X64.tar.xz": "old-x64",\n'
                '    "LLVM-22.1.7-macOS-ARM64.tar.xz": "old-mac",\n'
                "}\n",
                encoding="utf-8",
            )

            changed = update_llvm_distributions.update_module(module, self.release())

            self.assertTrue(changed)
            updated = module.read_text(encoding="utf-8")
            self.assertNotIn("22.1.7", updated)
            self.assertIn('"LLVM-22.1.8-Linux-ARM64.tar.xz": "' + "1".zfill(64), updated)
            self.assertIn('"LLVM-22.1.8-macOS-ARM64.tar.xz": "' + "3".zfill(64), updated)

    def test_rejects_asset_without_sha256_digest(self) -> None:
        with self.assertRaisesRegex(ValueError, "has no SHA-256 digest"):
            update_llvm_distributions.llvm_distributions(
                "22.1.8", self.release(missing_digest=True)
            )


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