#!/usr/bin/env bash
#
# note - quick scratch notes from the terminal
#
# append notes, search, or open in editor

# shellcheck disable=SC2250

set -eu

NOTES_DIR="${NOTES_DIR:-${HOME}/notes}"
NOTES_FILE="${NOTES_DIR}/scratch.md"

print_help() {
  printf %s "\
Usage: note [options] [text...]

Quick scratch notes from the terminal

Commands:
  note <text>           Append a note with timestamp
  note                  Open notes in \$EDITOR
  note --today          Show today's notes
  note --search <term>  Search notes
  note --list           List last 20 notes
  note --edit           Open notes in \$EDITOR
  note --path           Print notes file path
  -h, --help            Show this help message

Environment:
  NOTES_DIR    Directory for notes (default: ~/notes)

Examples:
  note remember to update the API key
  note \"meeting at 3pm with design team\"
  note --today
  note --search api
"
  exit 0
}

log() {
  printf '%s\n' "$@"
}

die() {
  printf '%s\n' "$*" >&2
  exit 1
}

ensure_notes_dir() {
  if [ ! -d "${NOTES_DIR}" ]; then
    mkdir -p "${NOTES_DIR}"
  fi
  if [ ! -f "${NOTES_FILE}" ]; then
    printf '%b' "# scratch notes" >"${NOTES_FILE}"
    printf '\n' >>"${NOTES_FILE}"
  fi
}

add_note() {
  ensure_notes_dir
  timestamp=$(date "+%Y-%m-%d %H:%M")
  text="$*"

  printf '%b' "- **[$timestamp]** ${text}" >>"${NOTES_FILE}"
  log "Noted: ${text}"
}

show_today() {
  ensure_notes_dir
  today=$(date "+%Y-%m-%d")

  found=$(grep "$today" "${NOTES_FILE}" 2>/dev/null || true)

  if [ -n "${found}" ]; then
    log "Notes from today (${today}):"
    printf '\n'
    log "${found}"
  else
    log "No notes from today."
  fi
}

search_notes() {
  ensure_notes_dir
  term="$1"

  grep --color=always -E -i "$term" "${NOTES_FILE}" || log "No matches for '${term}'"
}

list_notes() {
  ensure_notes_dir
  log "Last 20 notes:"
  printf '\n'
  grep "^- \*\*\[" "${NOTES_FILE}" 2>/dev/null | tail -20 || log "No notes yet."
}

open_in_editor() {
  ensure_notes_dir
  ${EDITOR:-vim} "${NOTES_FILE}"
}

# Main
if [ "$#" -eq 0 ]; then
  open_in_editor
  exit 0
fi

case "$1" in
  -h | --help)
    print_help
    ;;
  --today)
    show_today
    ;;
  --search)
    if [ "$#" -lt 2 ]; then
      die "usage: note --search <term>"
    fi
    search_notes "$2"
    ;;
  --list)
    list_notes
    ;;
  --edit)
    open_in_editor
    ;;
  --path)
    log "${NOTES_FILE}"
    ;;
  *)
    add_note "$@"
    ;;
esac
