"""Runnable Wails app launcher rule."""

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

def _wails_run_impl(ctx):
    launcher = ctx.actions.declare_file(ctx.label.name)

    resolve_lines = """
tool="$(resolve_runfile "{tool_short_path}")"
binary="$(resolve_runfile "{binary_short_path}")"
build_assets="$(resolve_runfile "{build_assets_short_path}")"
icon=""
if [[ -n "{icon_short_path}" ]]; then
  icon="$(resolve_runfile "{icon_short_path}")"
fi
""".format(
        tool_short_path = ctx.executable._tool.short_path,
        binary_short_path = ctx.executable.binary.short_path,
        build_assets_short_path = ctx.files.build_assets[0].short_path,
        icon_short_path = ctx.file.icon.short_path if ctx.file.icon else "",
    )

    command_lines = """
exec "$tool" \
  --binary "$binary" \
  --build-assets "$build_assets" \
  --frontend-url {frontend_url} \
  --icon "$icon" \
  --mode {mode}
""".format(
        frontend_url = _shell_quote(ctx.attr.frontend_url),
        mode = _shell_quote(ctx.attr.mode),
    )

    ctx.actions.write(
        output = launcher,
        is_executable = True,
        content = bash_launcher(resolve_lines, command_lines),
    )

    transitive_files = [
        ctx.attr._tool[DefaultInfo].default_runfiles.files,
        ctx.attr.binary[DefaultInfo].default_runfiles.files,
    ]

    runfiles = ctx.runfiles(
        files = [
            ctx.executable._tool,
            ctx.executable.binary,
        ] + ctx.files.build_assets + ([ctx.file.icon] if ctx.file.icon else []),
        transitive_files = depset(transitive = transitive_files),
    )

    return [DefaultInfo(executable = launcher, runfiles = runfiles)]

def _shell_quote(value):
    return "'" + value.replace("'", "'\"'\"'") + "'"

wails_run = rule(
    implementation = _wails_run_impl,
    doc = "Creates a runnable target that launches a Wails application.",
    attrs = {
        "binary": attr.label(
            mandatory = True,
            executable = True,
            cfg = "target",
        ),
        "build_assets": attr.label(
            mandatory = True,
            allow_files = True,
        ),
        "frontend_url": attr.string(default = "http://127.0.0.1:9245"),
        "icon": attr.label(
            allow_single_file = True,
        ),
        "mode": attr.string(
            default = "run",
            values = ["dev", "run"],
        ),
        "_tool": attr.label(
            default = "//wails/tools:launch_app",
            cfg = "exec",
            executable = True,
        ),
    },
    executable = True,
)
