"""Module extension to download CDDL spec files from w3c/webref at a pinned commit."""

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")

# Pinned to a single w3c/webref "main" commit (kept on main so pin-to-pin diffs
# stay auditable) and regenerated by the //scripts:update_cddl Bazel target:
# https://github.com/w3c/webref/tree/main/ed/cddl
_COMMIT = "42c791d397dec7b6aa6349e662824b0079e8f299"
_BASE_URL = "https://raw.githubusercontent.com/w3c/webref/{commit}/ed/cddl".format(commit = _COMMIT)

# The "-all" (union) CDDL file for each protocol in
# https://github.com/w3c/webref/tree/{commit}/ed/cddl -- the per-end
# "-local"/"-remote" splits are skipped since generation merges the union.
# Which of these actually feed generation is selected in the py/ and
# javascript/ BUILD.bazel merge lists (this pins a superset).
# Each entry is (repo_name, filename, sha256). Files are downloaded as
# "spec.cddl" in each repo, referenced as @<repo_name>//file:spec.cddl.
_CDDL_FILES = [
    ("at_driver_all_cddl", "at-driver-all.cddl", "f8502ca866e494d9c46a5209eb0cfec57107fffe587d154a365a19e8b93dd7aa"),
    ("digital_credentials_all_cddl", "digital-credentials-all.cddl", "83e955a6d53f43e0456f82a800712f683980aa53f4ba83aca58a551d256d6f04"),
    ("permissions_all_cddl", "permissions-all.cddl", "50e9b0017415e27a18a190bf37df048d4513f8432e42fe97901c9f2d55204b50"),
    ("prefetch_all_cddl", "prefetch-all.cddl", "51409b998176a81f681252f8ee16bea5a54a3be9d1cfee9f13ca34efd1feb5ea"),
    ("ua_client_hints_all_cddl", "ua-client-hints-all.cddl", "6bb41f05d09c755305226b7350970e54f6404698510ea2e1e7a931eaa2647aeb"),
    ("web_bluetooth_all_cddl", "web-bluetooth-all.cddl", "bc687d19c1e92cf4f0a37bbf7f9aa21db956344b34d8cdda4319b7f4615b6d1d"),
    ("webdriver_bidi_all_cddl", "webdriver-bidi-all.cddl", "9669d54fd388d07aab14f871de516844f94e06b5f0fee6bc572119d59f035ed7"),
]

def webref_cddl():
    for name, filename, sha256 in _CDDL_FILES:
        http_file(
            name = name,
            downloaded_file_path = "spec.cddl",
            sha256 = sha256,
            url = _BASE_URL + "/" + filename,
        )

def _webref_cddl_impl(_ctx):
    webref_cddl()

webref_cddl_extension = module_extension(
    implementation = _webref_cddl_impl,
)
