#!/usr/bin/env bash
set -euo pipefail

BIB="${BIB:-/home/lukasz/git/thesis_main/05_thesis/bibliography.bib}"
DMENU_KEY="${DMENU_KEY:-dmenu -i -l 20 -p Citekey}"
DMENU_LOC="${DMENU_LOC:-dmenu -i -p 'Locator (optional)'}"
CLIP="${CLIP:-xclip -selection clipboard}"

if [[ ! -r "$BIB" ]]; then
  printf "ERROR: cannot read %s\n" "$BIB" >&2
  exit 1
fi

# Build menu lines: "type<TAB>citekey"
choices="$(
  rg -n '^\@(\w+)\{([^,]+),' "$BIB" \
  | sed -E 's/^[0-9]+:\@(\w+)\{([^,]+),/\1\t\2/' \
  | sort -u
)"

picked="$(printf "%s\n" "$choices" | eval "$DMENU_KEY" || true)"
[[ -z "$picked" ]] && exit 0

key="$(printf "%s" "$picked" | awk -F'\t' '{print $2}')"
[[ -z "$key" ]] && exit 0

# Optional locator, e.g. 84 / 11-13 / xxi
locator="$(printf '\n' | eval "$DMENU_LOC" || true)"

if [[ -n "${locator// }" ]]; then
  citation="[@$key, $locator]"
else
  citation="[@$key]"
fi

printf "%s" "$citation" | eval "$CLIP"
printf "Copied: %s\n" "$citation" >&2
