#!/bin/bash

# omarchy:summary=Prompt for text input from a menu
# omarchy:group=menu
# omarchy:name=input
# omarchy:args=prompt [menu args...]
# omarchy:examples=omarchy menu input Reminder|omarchy-menu-input "Reminder in minutes" --width 400

set -euo pipefail

prompt="${1:-Input}"
if (( $# > 0 )); then
  shift
fi

menu_width=""

while (( $# > 0 )); do
  case "$1" in
    --width)
      shift
      if (( $# == 0 )); then
        echo "omarchy-menu-input: --width requires a value" >&2
        exit 1
      fi
      menu_width="$1"
      ;;
  esac
  shift
done

work_dir=$(mktemp -d)
selection_file="$work_dir/selection"
done_file="$work_dir/done"
: >"$selection_file"
trap 'rm -rf "$work_dir"' EXIT

payload=$(jq -nc \
  --arg prompt "$prompt" \
  --arg selectionFile "$selection_file" \
  --arg doneFile "$done_file" \
  --arg width "$menu_width" \
  '
    {
      mode: "input",
      prompt: $prompt,
      selectionFile: $selectionFile,
      doneFile: $doneFile
    }
    + (if ($width | length) > 0 then { width: ($width | tonumber? // 0 | trunc) } else {} end)
  ')

omarchy-shell shell summon omarchy.menu "$payload" >/dev/null

while [[ ! -e $done_file ]]; do
  sleep 0.05
done

if [[ -s $selection_file ]]; then
  cat "$selection_file"
else
  exit 1
fi
