#!/usr/bin/env bash
# cadmus — dark, live spell picker (fuzzel + hunspell).
# Named after the mythological founder who brought the alphabet to Greece.
# Type/select a word in the popup; selection is copied to the clipboard.

set -euo pipefail

DICT="${CADMUS_DICT:-en_US}"
APP="cadmus"
WORDS_FILE="${CADMUS_WORDS_FILE:-/usr/share/dict/words}"
CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/cadmus"
WORD_CACHE="$CACHE_DIR/words.txt"

die() { notify-send -a "$APP" -i dialog-error "$APP" "$1" >/dev/null 2>&1 || true; exit 1; }

for bin in fuzzel hunspell wl-copy wl-paste; do
    command -v "$bin" >/dev/null || die "missing dependency: $bin"
done

build_cache() {
    [[ -f "$WORDS_FILE" ]] || die "missing dictionary source: $WORDS_FILE"
    mkdir -p "$CACHE_DIR"
    awk '
        length($0) >= 2 && length($0) <= 24 &&
        $0 ~ /^[A-Za-z][A-Za-z-]*$/ {
            print tolower($0)
        }
    ' "$WORDS_FILE" | sort -u > "$WORD_CACHE"
}

[[ -s "$WORD_CACHE" ]] || build_cache

# Prefill input with primary selection (highlight a word, hit hotkey).
seed="$(wl-paste --primary 2>/dev/null | tr -d '\r\n' | awk '{print $1}')"
seed="$(printf '%s' "$seed" | tr '[:upper:]' '[:lower:]')"

word=$(
    fuzzel --dmenu \
           --prompt "spell> " \
           --placeholder "type a word…" \
           --search "$seed" \
           --match-mode fuzzy \
           --width 40 \
           --lines 10 \
           --background-color 1e1e2eff \
           --text-color cdd6f4ff \
           --input-color f5e0dcff \
           --prompt-color 89b4faff \
           --placeholder-color 6c7086ff \
           --match-color f9e2afff \
           --selection-color 313244ff \
           --selection-text-color ffffffff \
           --border-color 89b4faff \
           --border-width 2 \
           --border-radius 12 \
           < "$WORD_CACHE"
) || exit 0

word="$(printf '%s' "$word" | tr -d '\r\n' | awk '{$1=$1};1' | tr '[:upper:]' '[:lower:]')"
[[ -z "$word" ]] && exit 0

line=$(printf '%s\n' "$word" | hunspell -d "$DICT" -a 2>/dev/null | awk 'NR>1 && NF{print; exit}')

copy() { printf '%s' "$1" | wl-copy; }

case "${line:-}" in
    '*'|'+ '*|'')
        copy "$word"
        notify-send -a "$APP" -i dialog-ok-apply "✓ $word" "spelled correctly · copied"
        ;;
    '#'*)
        copy "$word"
        notify-send -a "$APP" -i dialog-warning "$word" "not in dictionary · copied anyway"
        exit 0
        ;;
    '&'*)
        best="$(printf '%s' "$line" | sed -E 's/^& [^:]+: ([^,]+).*/\1/' | sed 's/^ //')"
        copy "$word"
        notify-send -a "$APP" -i dialog-information "Copied: $word" "did you mean: $best"
        ;;
    *)
        notify-send -a "$APP" -i dialog-warning "Unexpected hunspell output" "$line"
        exit 1
        ;;
esac
