#!/bin/bash

# omarchy:summary=Open a clipboard history entry
# omarchy:group=clipboard
# omarchy:args=--history-index <index>
# omarchy:hidden=true

history_index=""
history_path="$HOME/.local/state/omarchy/clipboard-history.json"

while (( $# > 0 )); do
  case "$1" in
    --history-index)
      if (( $# < 2 )); then
        echo "Usage: omarchy-clipboard-open --history-index <index>" >&2
        exit 1
      fi
      history_index="$2"
      shift 2
      ;;
    *)
      echo "Usage: omarchy-clipboard-open --history-index <index>" >&2
      exit 1
      ;;
  esac
done

[[ $history_index =~ ^[0-9]+$ ]] || exit 1
[[ -r $history_path ]] || exit 1

entry_data=$(jq -er --argjson index "$history_index" '
  .[$index] |
  if type != "object" then error("missing")
  elif .type == "image" and (.path | type == "string") then "image\n" + .path + "x"
  elif .type == "text" and (.text | type == "string") then "text\n" + .text + "x"
  else error("unsupported")
  end
' "$history_path" 2>/dev/null) || exit 1

entry_data=${entry_data%x}
entry_type=${entry_data%%$'\n'*}
entry_value=${entry_data#*$'\n'}

open_image() {
  local path="$1"

  [[ -r $path ]] || exit 1
  exec omasnap --notify "$path"
}

open_text() {
  local text="$1"
  local url=""
  local open_dir=""
  local open_file=""

  url=$(grep -Eom1 'https?://[^[:space:]"'\''<>]+' <<<"$text" || true)
  if [[ -z $url && $text =~ ^[[:space:]]*([[:alnum:]][[:alnum:].-]+\.[[:alpha:]]{2,})(/[^[:space:]]*)?[[:space:]]*$ ]]; then
    url="https://${BASH_REMATCH[1]}${BASH_REMATCH[2]}"
  fi

  if [[ -n $url ]]; then
    exec omarchy-launch-browser "$url"
  fi

  open_dir="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/clipboard-open"
  mkdir -p "$open_dir"
  open_file=$(mktemp --tmpdir="$open_dir" clipboard.XXXXXX.txt) || exit 1
  printf '%s' "$text" >"$open_file"
  exec omarchy-launch-editor "$open_file"
}

case "$entry_type" in
  image)
    open_image "$entry_value"
    ;;
  text)
    open_text "$entry_value"
    ;;
  *)
    exit 1
    ;;
esac
