#!/usr/bin/env bash
# launch-kit statusline wrapper.
# Runs the user's original statusline command, then appends MCP chip output.
# Reads Claude Code's statusline JSON from stdin once, fans it out.
#
# The original command is stored under `_launchKitStatuslineOriginal.command`
# in ~/.claude/settings.json (written by `launch-kit statusline activate`).
# `launch-kit statusline deactivate` restores it to `statusLine.command`.
set -u

input=$(cat)
settings="$HOME/.claude/settings.json"

original_cmd=""
if [ -f "$settings" ] && command -v jq >/dev/null 2>&1; then
  original_cmd=$(jq -r '._launchKitStatuslineOriginal.command // empty' "$settings" 2>/dev/null || true)
fi

original_output=""
if [ -n "$original_cmd" ]; then
  original_output=$(printf '%s' "$input" | bash -c "$original_cmd" 2>/dev/null || true)
fi

cwd=""
if command -v jq >/dev/null 2>&1; then
  cwd=$(printf '%s' "$input" | jq -r '.workspace.current_dir // .cwd // empty' 2>/dev/null || true)
fi

chips=""
if [ -x "$HOME/.launchsecure/statusline-mcp.sh" ]; then
  # Build args array conditionally; `set -u` + empty `"${args[@]}"` would
  # error on bash 4 (default macOS bash), so test length before expanding.
  args=()
  [ -n "${LK_STATUSLINE_SHOW:-}" ] && args+=("--show=$LK_STATUSLINE_SHOW")
  [ "${LK_STATUSLINE_COMPACT:-0}" = "1" ] && args+=("--compact")
  if [ "${#args[@]}" -eq 0 ]; then
    chips=$(LK_STATUSLINE_CWD="$cwd" "$HOME/.launchsecure/statusline-mcp.sh" 2>/dev/null || true)
  else
    chips=$(LK_STATUSLINE_CWD="$cwd" "$HOME/.launchsecure/statusline-mcp.sh" "${args[@]}" 2>/dev/null || true)
  fi
fi

# Layout: by default the chips go on their OWN line below the user's original
# statusline (Claude Code renders each stdout newline as a new row). Set
# LK_STATUSLINE_INLINE=1 to keep the old single-line ` | `-joined layout.
if [ "${LK_STATUSLINE_INLINE:-0}" = "1" ]; then
  sep=$'\033[2m | \033[0m'
else
  sep=$'\n'
fi
if [ -n "$original_output" ] && [ -n "$chips" ]; then
  printf '%s%s%s' "$original_output" "$sep" "$chips"
elif [ -n "$original_output" ]; then
  printf '%s' "$original_output"
elif [ -n "$chips" ]; then
  printf '%s' "$chips"
fi
