# shellcheck shell=bash

gw_env_copy_bin() {
  local candidate=""

  if [[ -n "${GW_ENV_COPY_BIN:-}" && -x "$GW_ENV_COPY_BIN" ]]; then
    printf '%s\n' "$GW_ENV_COPY_BIN"
    return 0
  fi

  if [[ -n "${SCRIPT_DIR:-}" ]]; then
    candidate="$SCRIPT_DIR/gw-env-copy"
    if [[ -x "$candidate" ]]; then
      printf '%s\n' "$candidate"
      return 0
    fi
    candidate="$SCRIPT_DIR/gw-tui/target/release/gw-env-copy"
    if [[ -x "$candidate" ]]; then
      printf '%s\n' "$candidate"
      return 0
    fi
    candidate="$SCRIPT_DIR/gw-tui/target/debug/gw-env-copy"
    if [[ -x "$candidate" ]]; then
      printf '%s\n' "$candidate"
      return 0
    fi
  fi

  if [[ -n "${GW_ORCHESTRATOR_ROOT:-}" ]]; then
    candidate="$GW_ORCHESTRATOR_ROOT/gw-env-copy"
    if [[ -x "$candidate" ]]; then
      printf '%s\n' "$candidate"
      return 0
    fi
  fi

  if command -v gw-env-copy >/dev/null 2>&1; then
    command -v gw-env-copy
    return 0
  fi

  return 1
}

gw_env_copy_files() {
  local source_root="$1"
  local target_root="$2"
  local repo_root="${3:-$source_root}"

  local bin
  if ! bin="$(gw_env_copy_bin)"; then
    if declare -f err >/dev/null 2>&1; then
      err "gw-env-copy binary not found"
    else
      printf 'Error: %s\n' "gw-env-copy binary not found" >&2
    fi
    return 1
  fi

  "$bin" \
    --source "$source_root" \
    --target "$target_root" \
    --repo "$repo_root" \
    --format text
}
