"Repository rule that downloads a pre-compiled protoc from our official release for a single platform."

load("//toolchain:platforms.bzl", "PROTOBUF_PLATFORMS")
load(":tool_integrity.bzl", "RELEASED_BINARY_INTEGRITY", "RELEASE_VERSION")

def release_version_to_artifact_name(release_version, platform):
    # versions have a "v" prefix like "v28.0"
    stripped_version = release_version.removeprefix("v")

    # release candidate versions like "v29.0-rc3" have artifact names
    # like "protoc-29.0-rc-3-osx-x86_64.zip"
    artifact_version = stripped_version.replace("rc", "rc-")

    return "{}-{}-{}.zip".format(
        "protoc",
        artifact_version,
        platform,
    )

def _prebuilt_protoc_repo_impl(rctx):
    filename = release_version_to_artifact_name(
        RELEASE_VERSION,
        rctx.attr.platform,
    )
    rctx.download_and_extract(
        url = "https://github.com/protocolbuffers/protobuf/releases/download/{}/{}".format(
            RELEASE_VERSION,
            filename,
        ),
        sha256 = RELEASED_BINARY_INTEGRITY[filename],
    )

    rctx.file("BUILD.bazel", """\
# Generated by @protobuf//bazel/private/oss/toolchains/prebuilt:protoc_toolchain.bzl
load("@com_google_protobuf//bazel/toolchains:proto_toolchain.bzl", "proto_toolchain")

package(default_visibility = ["//visibility:public"])

proto_toolchain(
    name = "prebuilt_protoc_toolchain",
    proto_compiler = "{protoc_label}",
)
""".format(
        protoc_label = "bin/protoc.exe" if rctx.attr.platform.startswith("win") else "bin/protoc",
    ))

    # Bazel <8.3.0 lacks rctx.repo_metadata
    if not hasattr(rctx, "repo_metadata"):
        return None

    return rctx.repo_metadata(reproducible = True)

prebuilt_protoc_repo = repository_rule(
    doc = "Download a pre-built protoc and create a concrete toolchains for it",
    implementation = _prebuilt_protoc_repo_impl,
    attrs = {
        "platform": attr.string(
            doc = "A platform that protobuf ships a release for",
            mandatory = True,
            values = PROTOBUF_PLATFORMS.keys(),
        ),
    },
)
