"""Shared helpers for Wails rules."""

def _normalize_prefix(prefix):
    if not prefix or prefix == ".":
        return ""

    normalized = prefix.strip("/")
    if not normalized:
        return ""

    return normalized + "/"

def _manifest_rel_path(short_path, strip_prefix):
    normalized_prefix = _normalize_prefix(strip_prefix)
    rel_path = short_path

    if normalized_prefix and rel_path.startswith(normalized_prefix):
        rel_path = rel_path[len(normalized_prefix):]

    return rel_path

def write_manifest(ctx, name, files, strip_prefix = ""):
    manifest = ctx.actions.declare_file(name)
    lines = []

    for src in files:
        lines.append("%s\t%s" % (src.path, _manifest_rel_path(src.short_path, strip_prefix)))

    ctx.actions.write(
        output = manifest,
        content = "\n".join(lines) + "\n",
    )

    return manifest

def bash_launcher(resolve_lines, command_lines):
    return """#!/usr/bin/env bash
set -euo pipefail

runfiles_dir="${{RUNFILES_DIR:-$0.runfiles}}"
export RUNFILES_DIR="${{runfiles_dir}}"
export RUNFILES="${{runfiles_dir}}"
resolve_runfile() {{
  local short_path="$1"

  if [[ "$short_path" == ../* ]]; then
    echo "${{runfiles_dir}}/${{short_path#../}}"
  else
    echo "${{runfiles_dir}}/_main/${{short_path}}"
  fi
}}

{resolve_lines}
{command_lines}
""".format(
        resolve_lines = resolve_lines.strip(),
        command_lines = command_lines.strip(),
    )
