#!/bin/bash

# omarchy:summary=Copy text to the clipboard and type or paste it
# omarchy:group=clipboard
# omarchy:args=[--shift-insert|--universal] [--copy-only] [--history-index <index>|<text>]
# omarchy:examples=omarchy clipboard paste text "hello" | omarchy clipboard paste text --shift-insert "hello"
# omarchy:hidden=true

use_shift_insert=false
use_universal=false
copy_only=false
history_index=""
text=""

while (( $# > 0 )); do
  case "$1" in
    --shift-insert)
      use_shift_insert=true
      shift
      ;;
    --universal)
      use_universal=true
      shift
      ;;
    --copy-only)
      copy_only=true
      shift
      ;;
    --history-index)
      if (( $# < 2 )); then
        echo "Usage: omarchy-clipboard-paste-text [--shift-insert|--universal] [--copy-only] [--history-index <index>|<text>]" >&2
        exit 1
      fi
      history_index="$2"
      shift 2
      ;;
    *)
      break
      ;;
  esac
done

copy_history_entry() {
  local history_path="$HOME/.local/state/omarchy/clipboard-history.json"
  local entry_json

  [[ $history_index =~ ^[0-9]+$ ]] || exit
  [[ -r $history_path ]] || exit
  entry_json=$(jq -ce --argjson index "$history_index" '
    .[$index] | select(type == "object" and .type == "text" and (.text | type == "string")) | .text
  ' "$history_path" 2>/dev/null) || exit
  jq -rj '.' <<<"$entry_json" | wl-copy
}

if [[ -n $history_index ]]; then
  copy_history_entry
  if [[ $copy_only != "true" ]]; then
    use_shift_insert=true
  fi
else
  text=${1:-}
  [[ -n $text ]] || exit
  printf '%s' "$text" | wl-copy
fi

if [[ $copy_only == "true" ]]; then
  exit
fi

sleep 0.15

# Universal paste presses SUPER + V's own action: Ctrl+Shift+V in terminals,
# Ctrl+V everywhere else.
if [[ $use_universal == "true" ]]; then
  hyprctl dispatch 'o.universal_paste' >/dev/null 2>&1 || true
elif [[ $use_shift_insert == "true" ]]; then
  wtype -M shift -k Insert -m shift 2>/dev/null || true
else
  wtype -- "$text" 2>/dev/null || true
fi
