"""Rule for generating Wails build assets."""

load(":private/common.bzl", "write_manifest")

def _wails_build_assets_impl(ctx):
    toolchain = ctx.toolchains["//wails:toolchain_type"].wails
    out_dir = ctx.actions.declare_directory(ctx.label.name)
    manifest = write_manifest(ctx, ctx.label.name + ".manifest", ctx.files.srcs, ctx.attr.strip_prefix)

    args = ctx.actions.args()
    args.add("--app-name", ctx.attr.app_name)
    args.add("--binary-name", ctx.attr.binary_name)
    args.add("--config-file", ctx.attr.config_file)
    args.add("--manifest", manifest.path)
    args.add("--out", out_dir.path)
    args.add("--wails", toolchain.executable.path)
    if ctx.attr.macos_minimum_system_version:
        args.add("--macos-minimum-system-version", ctx.attr.macos_minimum_system_version)

    ctx.actions.run(
        executable = ctx.executable._tool,
        arguments = [args],
        inputs = depset(ctx.files.srcs + [manifest, toolchain.go_executable]),
        outputs = [out_dir],
        tools = [
            ctx.executable._tool,
            toolchain.files_to_run,
        ],
        env = {
            "GO_BIN": toolchain.go_executable.path,
        },
        mnemonic = "WailsBuildAssets",
        progress_message = "Generating Wails build assets for %s" % ctx.label,
    )

    return [DefaultInfo(files = depset([out_dir]))]

wails_build_assets = rule(
    implementation = _wails_build_assets_impl,
    doc = "Runs `wails update build-assets` in a staged build directory.",
    attrs = {
        "app_name": attr.string(mandatory = True),
        "binary_name": attr.string(mandatory = True),
        "config_file": attr.string(default = "config.yml"),
        "macos_minimum_system_version": attr.string(default = ""),
        "srcs": attr.label_list(
            mandatory = True,
            allow_files = True,
        ),
        "strip_prefix": attr.string(default = ""),
        "_tool": attr.label(
            default = "//wails/tools:build_assets_action",
            cfg = "exec",
            executable = True,
        ),
    },
    toolchains = ["//wails:toolchain_type"],
)
