#!/usr/bin/env bash
# =============================================================================
#  FoodGram by Page Telegram Volunteer Services
#  Daily food & drink journal
#
#  Log meals and drinks for any date or time, edit later, and print a
#  plain-text report from a text editor or word processor (US Letter).
# =============================================================================

if [[ -z "${BASH_VERSION:-}" ]]; then
  echo "ERROR: FoodGram requires bash. Run: bash $0" >&2
  exit 1
fi
if (( BASH_VERSINFO[0] < 4 )); then
  echo "ERROR: FoodGram requires bash 4 or newer." >&2
  exit 1
fi

# Arithmetic ((expr)) returns 1 when expr==0; do not use set -e.
set -uo pipefail

VERSION="1.0.0"
APP_SHORT="FoodGram"
APP_NAME="FoodGram by Page Telegram Volunteer Services"
APP_CREDIT="FoodGram by Page Telegram Volunteer Services"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Default next to the script so a pCloud/Documents copy keeps the journal.
DATA_DIR="${FOODGRAM_HOME:-$SCRIPT_DIR/data}"
DB_FILE="$DATA_DIR/entries.tsv"
LOCK_FILE="$DATA_DIR/.lock"
REPORT_DIR="$DATA_DIR/reports"

REPORT_WIDTH="${FOODGRAM_WIDTH:-72}"
DB_HEADER=$'id\tdate\ttime\tkind\tmeal\titem\tquantity\tingredients\tnotes'

# ── Colors (TTY only) ──────────────────────────────────────────────────────
R="" B="" D="" U=""
cRED="" cGRN="" cYLW="" cCYN="" cWHT="" cORG="" cDIM=""
if [[ -t 1 ]]; then
  R=$'\e[0m'    B=$'\e[1m'    D=$'\e[2m'    U=$'\e[4m'
  cRED=$'\e[91m'  cGRN=$'\e[92m'  cYLW=$'\e[93m'
  cCYN=$'\e[96m'  cWHT=$'\e[97m'  cORG=$'\e[38;5;208m'
  cDIM=$'\e[38;5;245m'
fi

# Parallel arrays — one slot per journal entry
IDS=() DATES=() TIMES=() KINDS=() MEALS=() ITEMS=() QTYS=() INGS=() NOTES=()
LAST_ID=""

# =============================================================================
#  Small helpers
# =============================================================================

have_cmd() { command -v "$1" >/dev/null 2>&1; }

ensure_dirs() {
  mkdir -p "$DATA_DIR" "$REPORT_DIR"
  [[ -f "$DB_FILE" ]] || printf '%s\n' "$DB_HEADER" > "$DB_FILE"
}

cls() { printf '\e[2J\e[H'; }

pause() {
  local msg="${1:-Press Enter to continue...}"
  if [[ -t 0 ]]; then
    IFS= read -r -p "  $msg" _ || true
  fi
}

trim() {
  local s="${1-}"
  s="${s#"${s%%[![:space:]]*}"}"
  s="${s%"${s##*[![:space:]]}"}"
  printf '%s' "$s"
}

# Strip CR, tabs, and newlines so a field stays on one TSV column.
clean_field() {
  local s="${1-}"
  s=${s//$'\r'/}
  s=${s//$'\t'/ }
  s=${s//$'\n'/; }
  printf '%s' "$s"
}

lc() { printf '%s' "${1-}" | tr '[:upper:]' '[:lower:]'; }

hr() {
  local ch="${1:--}" w="${2:-$REPORT_WIDTH}"
  local line
  printf -v line '%*s' "$w" ''
  printf '%s\n' "${line// /$ch}"
}

# Word-wrap at WIDTH. Optional PREFIX is prepended to every line.
wrap() {
  local text="${1-}" width="${2:-$REPORT_WIDTH}" prefix="${3-}"
  local inner=$((width - ${#prefix}))
  (( inner < 20 )) && inner=20
  [[ -z "$text" ]] && return 0
  if have_cmd fold; then
    printf '%s\n' "$text" | fold -s -w "$inner" | while IFS= read -r line || [[ -n "$line" ]]; do
      printf '%s%s\n' "$prefix" "$line"
    done
  else
    printf '%s%s\n' "$prefix" "$text"
  fi
}

today() { date +%F; }

# Accept today / yesterday / tomorrow / YYYY-MM-DD / GNU date phrases.
resolve_date() {
  local raw
  raw="$(trim "${1:-today}")"
  [[ -z "$raw" ]] && raw="today"
  case "$(lc "$raw")" in
    today|tod|t)     date +%F ;;
    yesterday|yday|y) date -d yesterday +%F ;;
    tomorrow|tom)    date -d tomorrow +%F ;;
    *)
      if [[ "$raw" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
        date -d "$raw" +%F 2>/dev/null || return 1
      else
        date -d "$raw" +%F 2>/dev/null || return 1
      fi
      ;;
  esac
}

# Accept HH:MM, H:MM, HHMM. Empty -> now.
resolve_time() {
  local raw
  raw="$(trim "${1-}")"
  if [[ -z "$raw" || "$(lc "$raw")" == "now" ]]; then
    date +%H:%M
    return 0
  fi
  raw="${raw//./:}"
  if [[ "$raw" =~ ^([0-9]{1,2}):([0-9]{2})$ ]]; then
    printf '%02d:%02d' "$((10#${BASH_REMATCH[1]}))" "$((10#${BASH_REMATCH[2]}))"
    return 0
  fi
  if [[ "$raw" =~ ^([0-9]{3,4})$ ]]; then
    local padded
    printf -v padded '%04d' "$((10#$raw))"
    printf '%s:%s' "${padded:0:2}" "${padded:2:2}"
    return 0
  fi
  return 1
}

valid_time() {
  local t="$1" h m
  [[ "$t" =~ ^([0-9]{2}):([0-9]{2})$ ]] || return 1
  h=$((10#${BASH_REMATCH[1]}))
  m=$((10#${BASH_REMATCH[2]}))
  (( h >= 0 && h <= 23 && m >= 0 && m <= 59 ))
}

fmt_date_long() {
  date -d "$1" +"%A, %B %-d, %Y" 2>/dev/null || printf '%s' "$1"
}

fmt_time_12() {
  date -d "$1" +"%-I:%M %p" 2>/dev/null || printf '%s' "$1"
}

normalize_kind() {
  case "$(lc "$(trim "${1-}")")" in
    1|f|food|eat|meal|eaten) echo food ;;
    2|d|drink|drinks|bev|beverage|water|coffee|tea) echo drink ;;
    *) return 1 ;;
  esac
}

normalize_meal() {
  case "$(lc "$(trim "${1-}")")" in
    1|b|bfast|breakfast|brk|morning) echo breakfast ;;
    2|l|lunch|noon) echo lunch ;;
    3|d|din|dinner|supper|evening) echo dinner ;;
    4|s|snack|snacks) echo snack ;;
    5|o|other|""|unspecified) echo other ;;
    *) return 1 ;;
  esac
}

kind_label() {
  case "$1" in
    drink) echo DRINK ;;
    *)     echo FOOD ;;
  esac
}

meal_title() {
  case "$1" in
    breakfast) echo BREAKFAST ;;
    lunch)     echo LUNCH ;;
    dinner)    echo DINNER ;;
    snack)     echo SNACKS ;;
    *)         echo OTHER ;;
  esac
}

# Read a line. Prefills DEFAULT when the terminal supports readline.
# Prints the reply (may be empty).
ask_line() {
  local prompt="$1" default="${2-}" reply=""
  if [[ -t 0 ]]; then
    if [[ -n "$default" ]]; then
      IFS= read -r -e -i "$default" -p "$prompt" reply || true
    else
      IFS= read -r -e -p "$prompt" reply || true
    fi
  else
    # Piped / scripted answers; blank line keeps the default.
    IFS= read -r reply || true
    [[ -z "$reply" ]] && reply="$default"
  fi
  printf '%s' "$reply"
}

confirm() {
  local prompt="${1:-Are you sure?}" reply=""
  if [[ ! -t 0 ]]; then
    return 1
  fi
  IFS= read -r -e -p "  $prompt [y/N] " reply || true
  case "$(lc "$reply")" in
    y|yes) return 0 ;;
    *)     return 1 ;;
  esac
}

# =============================================================================
#  Database
# =============================================================================

acquire_lock() {
  exec 9>>"$LOCK_FILE"
  if have_cmd flock; then
    flock 9
  fi
}

release_lock() {
  if have_cmd flock; then
    flock -u 9 2>/dev/null || true
  fi
}

# Split a TSV line into F[], keeping empty columns. `read` + IFS=tab
# treats tab as whitespace and collapses `field\t\tfield` into two fields.
parse_tsv() {
  local rest="$1"
  F=()
  while [[ "$rest" == *$'\t'* ]]; do
    F+=("${rest%%$'\t'*}")
    rest="${rest#*$'\t'}"
  done
  F+=("$rest")
}

load_db() {
  IDS=(); DATES=(); TIMES=(); KINDS=(); MEALS=()
  ITEMS=(); QTYS=(); INGS=(); NOTES=()
  [[ -f "$DB_FILE" ]] || return 0
  local line
  while IFS= read -r line || [[ -n "${line-}" ]]; do
    [[ -z "${line:-}" || "$line" == \#* ]] && continue
    parse_tsv "$line"
    [[ "${F[0]:-}" == "id" || -z "${F[0]:-}" ]] && continue
    IDS+=("${F[0]:-}")
    DATES+=("${F[1]:-}")
    TIMES+=("${F[2]:-}")
    KINDS+=("${F[3]:-}")
    MEALS+=("${F[4]:-}")
    ITEMS+=("${F[5]:-}")
    QTYS+=("${F[6]:-}")
    INGS+=("${F[7]:-}")
    NOTES+=("${F[8]:-}")
  done < "$DB_FILE"
}

write_db() {
  acquire_lock
  local tmp i
  tmp="$(mktemp "$DATA_DIR/.entries.XXXXXX")"
  {
    printf '%s\n' "$DB_HEADER"
    for i in "${!IDS[@]}"; do
      printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
        "$(clean_field "${IDS[$i]}")" \
        "$(clean_field "${DATES[$i]}")" \
        "$(clean_field "${TIMES[$i]}")" \
        "$(clean_field "${KINDS[$i]}")" \
        "$(clean_field "${MEALS[$i]}")" \
        "$(clean_field "${ITEMS[$i]}")" \
        "$(clean_field "${QTYS[$i]}")" \
        "$(clean_field "${INGS[$i]}")" \
        "$(clean_field "${NOTES[$i]}")"
    done
  } > "$tmp"
  mv -f "$tmp" "$DB_FILE"
  release_lock
}

next_id() {
  local max=0 id
  for id in "${IDS[@]+"${IDS[@]}"}"; do
    [[ "$id" =~ ^[0-9]+$ ]] && (( id > max )) && max=$id
  done
  echo $((max + 1))
}

index_of_id() {
  local target="$1" i
  for i in "${!IDS[@]}"; do
    [[ "${IDS[$i]}" == "$target" ]] && { printf '%s' "$i"; return 0; }
  done
  return 1
}

# Sorted indices matching DATE (empty DATE = all). Optional KIND/MEAL filters.
# Sets FILTERED as a global array of indices.
filter_entries() {
  local want_date="${1-}" want_kind="${2-}" want_meal="${3-}"
  local i pairs=()
  FILTERED=()
  for i in "${!IDS[@]}"; do
    [[ -n "$want_date" && "${DATES[$i]}" != "$want_date" ]] && continue
    [[ -n "$want_kind" && "${KINDS[$i]}" != "$want_kind" ]] && continue
    [[ -n "$want_meal" && "${MEALS[$i]}" != "$want_meal" ]] && continue
    pairs+=("${DATES[$i]}"$'\t'"${TIMES[$i]}"$'\t'"$(printf '%06d' "${IDS[$i]}")"$'\t'"$i")
  done
  (( ${#pairs[@]} == 0 )) && return 0
  local line
  while IFS= read -r line; do
    FILTERED+=("${line##*$'\t'}")
  done < <(printf '%s\n' "${pairs[@]}" | sort)
}

entries_in_range() {
  local from="$1" to="$2"
  local i pairs=()
  FILTERED=()
  for i in "${!IDS[@]}"; do
    [[ "${DATES[$i]}" < "$from" || "${DATES[$i]}" > "$to" ]] && continue
    pairs+=("${DATES[$i]}"$'\t'"${TIMES[$i]}"$'\t'"$(printf '%06d' "${IDS[$i]}")"$'\t'"$i")
  done
  (( ${#pairs[@]} == 0 )) && return 0
  local line
  while IFS= read -r line; do
    FILTERED+=("${line##*$'\t'}")
  done < <(printf '%s\n' "${pairs[@]}" | sort)
}

# Sets LAST_ID. Must be called in the current shell (not $()), so the
# in-memory arrays stay in sync with the file.
append_entry() {
  local date time kind meal item qty ing notes
  LAST_ID="$(next_id)"
  date="$1" time="$2" kind="$3" meal="$4"
  item="$5" qty="$6" ing="$7" notes="$8"
  IDS+=("$LAST_ID")
  DATES+=("$date")
  TIMES+=("$time")
  KINDS+=("$kind")
  MEALS+=("$meal")
  ITEMS+=("$item")
  QTYS+=("$qty")
  INGS+=("$ing")
  NOTES+=("$notes")
  write_db
}

update_entry() {
  local i="$1"
  DATES[$i]="$2"
  TIMES[$i]="$3"
  KINDS[$i]="$4"
  MEALS[$i]="$5"
  ITEMS[$i]="$6"
  QTYS[$i]="$7"
  INGS[$i]="$8"
  NOTES[$i]="$9"
  write_db
}

delete_entry() {
  local target="$1" i
  local n_ids=() n_dates=() n_times=() n_kinds=() n_meals=()
  local n_items=() n_qtys=() n_ings=() n_notes=()
  local found=0
  for i in "${!IDS[@]}"; do
    if [[ "${IDS[$i]}" == "$target" ]]; then
      found=1
      continue
    fi
    n_ids+=("${IDS[$i]}")
    n_dates+=("${DATES[$i]}")
    n_times+=("${TIMES[$i]}")
    n_kinds+=("${KINDS[$i]}")
    n_meals+=("${MEALS[$i]}")
    n_items+=("${ITEMS[$i]}")
    n_qtys+=("${QTYS[$i]}")
    n_ings+=("${INGS[$i]}")
    n_notes+=("${NOTES[$i]}")
  done
  (( found == 1 )) || return 1
  IDS=("${n_ids[@]+"${n_ids[@]}"}")
  DATES=("${n_dates[@]+"${n_dates[@]}"}")
  TIMES=("${n_times[@]+"${n_times[@]}"}")
  KINDS=("${n_kinds[@]+"${n_kinds[@]}"}")
  MEALS=("${n_meals[@]+"${n_meals[@]}"}")
  ITEMS=("${n_items[@]+"${n_items[@]}"}")
  QTYS=("${n_qtys[@]+"${n_qtys[@]}"}")
  INGS=("${n_ings[@]+"${n_ings[@]}"}")
  NOTES=("${n_notes[@]+"${n_notes[@]}"}")
  write_db
}

# Unique recent items, newest first. Sets RECENT_IDX to source indices.
recent_items() {
  local limit="${1:-12}" i seen="" name
  RECENT_IDX=()
  for (( i=${#IDS[@]}-1; i>=0; i-- )); do
    name="$(lc "${ITEMS[$i]}")"
    [[ -z "$name" ]] && continue
    [[ " $seen " == *" $name "* ]] && continue
    seen+=" $name"
    RECENT_IDX+=("$i")
    (( ${#RECENT_IDX[@]} >= limit )) && break
  done
}

# =============================================================================
#  Input: ingredients (first-class field)
# =============================================================================

# Split a comma- or semicolon-separated string into trimmed pieces.
# Appends onto the named array passed as $1... wait, bash nameref:
split_ingredients() {
  local raw="$1"
  local piece
  ING_PARTS=()
  raw="${raw//;/,}"
  IFS=',' read -ra _ing_tmp <<< "$raw"
  for piece in "${_ing_tmp[@]}"; do
    piece="$(trim "$piece")"
    [[ -n "$piece" ]] && ING_PARTS+=("$piece")
  done
}

join_ingredients() {
  local out="" p
  for p in "$@"; do
    p="$(trim "$p")"
    [[ -z "$p" ]] && continue
    if [[ -z "$out" ]]; then
      out="$p"
    else
      out="$out; $p"
    fi
  done
  printf '%s' "$out"
}

# Interactive ingredients editor.
# $1 = existing list (may be empty). Prints the new list.
read_ingredients() {
  local existing="${1-}" line
  local acc=()

  printf '\n' >&2
  printf '  %sIngredients%s\n' "$B" "$R" >&2
  printf '  %sEnter one per line, or a single comma-separated list.%s\n' "$cDIM" "$R" >&2
  printf '  %sEmpty line finishes.%s\n' "$cDIM" "$R" >&2
  if [[ -n "$existing" ]]; then
    printf '  %sCurrent:%s %s\n' "$cYLW" "$R" "$existing" >&2
    printf '  %sPress Enter on the first line to keep these.%s\n' "$cDIM" "$R" >&2
  fi

  local first=1
  while true; do
    IFS= read -r -e -p "    - " line || break
    line="$(trim "$line")"
    if [[ -z "$line" ]]; then
      if (( first == 1 )); then
        printf '%s' "$existing"
        return 0
      fi
      break
    fi
    first=0
    if [[ "$line" == *","* || "$line" == *";"* ]]; then
      split_ingredients "$line"
      acc+=("${ING_PARTS[@]+"${ING_PARTS[@]}"}")
    else
      acc+=("$line")
    fi
  done
  join_ingredients "${acc[@]+"${acc[@]}"}"
}

# =============================================================================
#  Display
# =============================================================================

banner() {
  printf '%s\n' "${cORG}${B}"
  printf '  +--------------------------------------------------------------+\n'
  printf '  |        FoodGram by Page Telegram Volunteer Services          |\n'
  printf '  |                 Daily Food & Drink Journal                   |\n'
  printf '  +--------------------------------------------------------------+\n'
  printf '%s' "$R"
  printf '  %sv%s%s\n\n' "$cDIM" "$VERSION" "$R"
}

print_entry_card() {
  local i="$1" show_id="${2:-1}"
  local id="${IDS[$i]}" date="${DATES[$i]}" time="${TIMES[$i]}"
  local kind="${KINDS[$i]}" meal="${MEALS[$i]}" item="${ITEMS[$i]}"
  local qty="${QTYS[$i]}" ing="${INGS[$i]}" notes="${NOTES[$i]}"

  printf '  %s#%s%s  %s %s  %s%s%s / %s\n' \
    "$cDIM" "$id" "$R" \
    "$(fmt_date_long "$date")" "$(fmt_time_12 "$time")" \
    "$cORG" "$(kind_label "$kind")" "$R" "$meal"
  printf '      %s%s%s\n' "$B" "$item" "$R"
  [[ -n "$qty" ]]   && printf '      Serving:     %s\n' "$qty"
  if [[ -n "$ing" ]]; then
    printf '      Ingredients: %s\n' "$ing"
  fi
  [[ -n "$notes" ]] && printf '      Notes:       %s\n' "$notes"
}

print_day_table() {
  local date="$1" i n=0
  filter_entries "$date"
  printf '  %s%s%s\n' "$B" "$(fmt_date_long "$date")" "$R"
  printf '  %s\n' "$date"
  if (( ${#FILTERED[@]} == 0 )); then
    printf '  %s(no entries)%s\n' "$cDIM" "$R"
    return 0
  fi
  printf '\n'
  printf '  %s%-4s %-8s %-10s %-6s %s%s\n' \
    "$cDIM" "#" "Time" "Meal" "Kind" "Item" "$R"
  printf '  %s%s%s\n' "$cDIM" "$(printf '%.62s' "$(hr - 72)")" "$R"
  for i in "${FILTERED[@]}"; do
    n=$((n + 1))
    printf '  %-4s %-8s %-10s %-6s %s\n' \
      "$n" \
      "$(fmt_time_12 "${TIMES[$i]}")" \
      "${MEALS[$i]}" \
      "${KINDS[$i]}" \
      "${ITEMS[$i]}"
  done
  printf '\n  %s%s entr%s%s\n' "$cDIM" "$n" "$( (( n==1 )) && echo y || echo ies )" "$R"
}

# Map a 1-based list number (from the current FILTERED set) to an index.
filtered_pick() {
  local n="$1"
  [[ "$n" =~ ^[0-9]+$ ]] || return 1
  (( n >= 1 && n <= ${#FILTERED[@]} )) || return 1
  printf '%s' "${FILTERED[$((n - 1))]}"
}

# =============================================================================
#  Add / edit
# =============================================================================

pick_kind() {
  local default="${1:-food}" reply k
  printf '  Kind:  [1] food   [2] drink\n' >&2
  reply="$(ask_line "  Kind: " "$default")"
  if k="$(normalize_kind "$reply")"; then
    printf '%s' "$k"
  else
    printf '%s' "$default"
  fi
}

pick_meal() {
  local default="${1:-other}" reply m
  printf '  Meal:  [1] breakfast  [2] lunch  [3] dinner  [4] snack  [5] other\n' >&2
  reply="$(ask_line "  Meal: " "$default")"
  if m="$(normalize_meal "$reply")"; then
    printf '%s' "$m"
  else
    printf '%s' "$default"
  fi
}

# Interactive (or flag-driven) add. Extra args become the item name.
cmd_add() {
  load_db
  local date="" time="" kind="" meal="" item="" qty="" ing="" notes=""
  local reuse=""

  while [[ $# -gt 0 ]]; do
    case "$1" in
      -d|--date)        date="${2-}"; shift 2 ;;
      -t|--time)        time="${2-}"; shift 2 ;;
      -k|--kind)        kind="${2-}"; shift 2 ;;
      -m|--meal)        meal="${2-}"; shift 2 ;;
      -i|--item)        item="${2-}"; shift 2 ;;
      -q|--qty|--quantity|--serving) qty="${2-}"; shift 2 ;;
      -g|--ingredients) ing="${2-}"; shift 2 ;;
      -n|--notes)       notes="${2-}"; shift 2 ;;
      -h|--help)
        cat <<'EOF'
Usage: foodgram.sh add [options] [item name...]

  -d, --date DATE           today, yesterday, YYYY-MM-DD, or a date phrase
  -t, --time HH:MM          24-hour time (default: now)
  -k, --kind food|drink
  -m, --meal breakfast|lunch|dinner|snack|other
  -i, --item NAME
  -q, --qty TEXT            serving / amount
  -g, --ingredients TEXT    semicolon- or comma-separated
  -n, --notes TEXT

Any leftover words are used as the item name. Missing fields are
prompted when the session is interactive.

Examples:
  foodgram.sh add
  foodgram.sh add --date yesterday --time 12:30 "Grilled cheese"
  foodgram.sh add -k drink -m breakfast -g "coffee, half-and-half" Coffee
EOF
        return 0
        ;;
      --) shift; break ;;
      -*)
        echo "Unknown option: $1" >&2
        return 2
        ;;
      *)
        if [[ -n "$item" ]]; then
          item+=" $1"
        else
          item="$1"
        fi
        shift
        ;;
    esac
  done
  while [[ $# -gt 0 ]]; do
    if [[ -n "$item" ]]; then item+=" $1"; else item="$1"; fi
    shift
  done

  local interactive=0
  [[ -t 0 ]] && interactive=1

  if (( interactive )); then
    printf '\n  %sAdd an entry%s  (any date or time — including past days)\n\n' "$B" "$R"
  fi

  # Date
  if [[ -z "$date" ]]; then
    if (( interactive )); then
      date="$(ask_line "  Date (today / yesterday / YYYY-MM-DD): " "$(today)")"
    else
      date="$(today)"
    fi
  fi
  if ! date="$(resolve_date "$date")"; then
    echo "Invalid date." >&2
    return 1
  fi

  # Time
  if [[ -z "$time" ]]; then
    if (( interactive )); then
      time="$(ask_line "  Time (HH:MM, 24-hour): " "$(date +%H:%M)")"
    else
      time="$(date +%H:%M)"
    fi
  fi
  if ! time="$(resolve_time "$time")" || ! valid_time "$time"; then
    echo "Invalid time (use HH:MM)." >&2
    return 1
  fi

  # Offer recent items as a shortcut
  if [[ -z "$item" && $interactive -eq 1 ]]; then
    recent_items 10
    if (( ${#RECENT_IDX[@]} > 0 )); then
      printf '\n  %sRecent items — type a number to reuse one%s\n' "$cDIM" "$R"
      local r n=1
      for r in "${RECENT_IDX[@]}"; do
        printf '    %2d) %s%s%s  %s(%s, %s)%s\n' \
          "$n" "$cWHT" "${ITEMS[$r]}" "$R" \
          "$cDIM" "${KINDS[$r]}" "${MEALS[$r]}" "$R"
        n=$((n + 1))
      done
      printf '\n'
    fi
    item="$(ask_line "  Item name: " "")"
    if [[ "$item" =~ ^[0-9]+$ ]] && (( ${#RECENT_IDX[@]} > 0 )); then
      local pick=$((item))
      if (( pick >= 1 && pick <= ${#RECENT_IDX[@]} )); then
        reuse="${RECENT_IDX[$((pick - 1))]}"
        item="${ITEMS[$reuse]}"
        [[ -z "$kind" ]] && kind="${KINDS[$reuse]}"
        [[ -z "$meal" ]] && meal="${MEALS[$reuse]}"
        [[ -z "$qty"  ]] && qty="${QTYS[$reuse]}"
        [[ -z "$ing"  ]] && ing="${INGS[$reuse]}"
        printf '  %sReusing:%s %s\n' "$cGRN" "$R" "$item"
      fi
    fi
  fi

  item="$(trim "$item")"
  if [[ -z "$item" ]]; then
    echo "Item name is required." >&2
    return 1
  fi
  item="$(clean_field "$item")"

  if [[ -z "$kind" ]]; then
    if (( interactive )); then
      kind="$(pick_kind "${kind:-food}")"
    else
      kind="food"
    fi
  fi
  kind="$(normalize_kind "$kind" || echo food)"

  if [[ -z "$meal" ]]; then
    if (( interactive )); then
      meal="$(pick_meal "${meal:-other}")"
    else
      meal="other"
    fi
  fi
  meal="$(normalize_meal "$meal" || echo other)"

  if [[ -z "$qty" && $interactive -eq 1 ]]; then
    qty="$(ask_line "  Serving / amount (optional): " "${qty-}")"
  fi
  qty="$(clean_field "$(trim "$qty")")"

  if (( interactive )); then
    ing="$(read_ingredients "$ing")"
  elif [[ -n "$ing" ]]; then
    split_ingredients "$ing"
    ing="$(join_ingredients "${ING_PARTS[@]+"${ING_PARTS[@]}"}")"
  fi
  ing="$(clean_field "$ing")"

  if [[ -z "$notes" && $interactive -eq 1 ]]; then
    notes="$(ask_line "  Notes (optional): " "")"
  fi
  notes="$(clean_field "$(trim "$notes")")"

  append_entry "$date" "$time" "$kind" "$meal" "$item" "$qty" "$ing" "$notes"
  printf '\n  %sSaved%s entry #%s  (%s %s)\n\n' "$cGRN" "$R" "$LAST_ID" "$date" "$time"
  local idx
  idx="$(index_of_id "$LAST_ID")" && print_entry_card "$idx"
  printf '\n'
}

cmd_edit() {
  load_db
  local target="${1-}" i

  if [[ -z "$target" ]]; then
    if [[ ! -t 0 ]]; then
      echo "Usage: foodgram.sh edit <id>" >&2
      return 2
    fi
    printf '\n  Enter an entry #, or a date to pick from that day.\n'
    target="$(ask_line "  Id or date: " "$(today)")"
  fi

  if [[ "$target" =~ ^[0-9]+$ ]] && i="$(index_of_id "$target")"; then
    :
  else
    local day
    if ! day="$(resolve_date "$target")"; then
      echo "No entry with that id, and that is not a valid date." >&2
      return 1
    fi
    filter_entries "$day"
    if (( ${#FILTERED[@]} == 0 )); then
      echo "No entries on $day." >&2
      return 1
    fi
    printf '\n'
    print_day_table "$day"
    printf '\n'
    local pick
    pick="$(ask_line "  Edit which # (list number or entry id): " "")"
    if i="$(filtered_pick "$pick")"; then
      :
    elif [[ "$pick" =~ ^[0-9]+$ ]] && i="$(index_of_id "$pick")"; then
      :
    else
      echo "Invalid selection." >&2
      return 1
    fi
  fi

  printf '\n  %sEditing entry #%s%s\n' "$B" "${IDS[$i]}" "$R"
  printf '  %sLeave a field as-is, or change it. Date and time may be in the past.%s\n\n' "$cDIM" "$R"

  local date time kind meal item qty ing notes
  date="$(ask_line "  Date: " "${DATES[$i]}")"
  if ! date="$(resolve_date "$date")"; then
    echo "Invalid date." >&2
    return 1
  fi
  time="$(ask_line "  Time (HH:MM): " "${TIMES[$i]}")"
  if ! time="$(resolve_time "$time")" || ! valid_time "$time"; then
    echo "Invalid time." >&2
    return 1
  fi
  kind="$(pick_kind "${KINDS[$i]}")"
  meal="$(pick_meal "${MEALS[$i]}")"
  item="$(ask_line "  Item: " "${ITEMS[$i]}")"
  item="$(clean_field "$(trim "$item")")"
  [[ -z "$item" ]] && { echo "Item name is required." >&2; return 1; }
  qty="$(ask_line "  Serving / amount: " "${QTYS[$i]}")"
  qty="$(clean_field "$(trim "$qty")")"

  printf '\n  %sIngredients%s (edit the line, or type . to re-enter one per line)\n' "$B" "$R"
  ing="$(ask_line "  Ingredients: " "${INGS[$i]}")"
  if [[ "$ing" == "." ]]; then
    ing="$(read_ingredients "${INGS[$i]}")"
  fi
  ing="$(clean_field "$ing")"
  notes="$(ask_line "  Notes: " "${NOTES[$i]}")"
  notes="$(clean_field "$(trim "$notes")")"

  update_entry "$i" "$date" "$time" "$kind" "$meal" "$item" "$qty" "$ing" "$notes"
  printf '\n  %sUpdated%s entry #%s\n\n' "$cGRN" "$R" "${IDS[$i]}"
  print_entry_card "$i"
  printf '\n'
}

cmd_delete() {
  load_db
  local target="${1-}" i
  if [[ -z "$target" ]]; then
    if [[ ! -t 0 ]]; then
      echo "Usage: foodgram.sh delete <id>" >&2
      return 2
    fi
    target="$(ask_line "  Delete entry id (or date to pick): " "")"
  fi

  if [[ "$target" =~ ^[0-9]+$ ]] && i="$(index_of_id "$target")"; then
    :
  else
    local day
    if ! day="$(resolve_date "$target")"; then
      echo "No such entry." >&2
      return 1
    fi
    filter_entries "$day"
    (( ${#FILTERED[@]} > 0 )) || { echo "No entries on $day." >&2; return 1; }
    print_day_table "$day"
    local pick
    pick="$(ask_line "  Delete which # (list number or entry id): " "")"
    if i="$(filtered_pick "$pick")"; then
      :
    elif [[ "$pick" =~ ^[0-9]+$ ]] && i="$(index_of_id "$pick")"; then
      :
    else
      echo "Invalid selection." >&2
      return 1
    fi
  fi

  printf '\n'
  print_entry_card "$i"
  printf '\n'
  if [[ -t 0 ]]; then
    confirm "Delete entry #${IDS[$i]}?" || { echo "  Cancelled."; return 0; }
  fi
  delete_entry "${IDS[$i]}" || { echo "Delete failed." >&2; return 1; }
  printf '  %sDeleted.%s\n' "$cGRN" "$R"
}

# Copy an existing entry onto a (possibly different) date/time.
cmd_copy() {
  load_db
  local src="${1-}" dest_date="${2:-$(today)}" dest_time="${3:-$(date +%H:%M)}"
  local i
  if [[ -z "$src" ]]; then
    echo "Usage: foodgram.sh copy <id> [date] [time]" >&2
    return 2
  fi
  i="$(index_of_id "$src")" || { echo "No entry #$src." >&2; return 1; }
  dest_date="$(resolve_date "$dest_date")" || { echo "Invalid date." >&2; return 1; }
  dest_time="$(resolve_time "$dest_time")" || { echo "Invalid time." >&2; return 1; }
  valid_time "$dest_time" || { echo "Invalid time." >&2; return 1; }
  append_entry "$dest_date" "$dest_time" "${KINDS[$i]}" "${MEALS[$i]}" \
    "${ITEMS[$i]}" "${QTYS[$i]}" "${INGS[$i]}" "${NOTES[$i]}"
  printf '  Copied #%s → #%s  (%s %s)  %s\n' "$src" "$LAST_ID" "$dest_date" "$dest_time" "${ITEMS[$i]}"
}

# =============================================================================
#  List / search / day browser
# =============================================================================

cmd_list() {
  load_db
  local spec="${1:-today}"
  local from to
  case "$(lc "$spec")" in
    all)
      entries_in_range "0000-01-01" "9999-12-31"
      if (( ${#FILTERED[@]} == 0 )); then
        echo "  (journal is empty)"
        return 0
      fi
      local last="" i
      for i in "${FILTERED[@]}"; do
        if [[ "${DATES[$i]}" != "$last" ]]; then
          last="${DATES[$i]}"
          printf '\n'
          printf '  %s%s%s\n' "$B" "$(fmt_date_long "$last")" "$R"
        fi
        printf '  #%s  %s  %-10s %-6s %s\n' \
          "${IDS[$i]}" "$(fmt_time_12 "${TIMES[$i]}")" \
          "${MEALS[$i]}" "${KINDS[$i]}" "${ITEMS[$i]}"
      done
      printf '\n'
      return 0
      ;;
    week|--week)
      from="$(date -d '6 days ago' +%F)"
      to="$(today)"
      cmd_report --from "$from" --to "$to" --stdout
      return
      ;;
  esac
  local day
  day="$(resolve_date "$spec")" || { echo "Invalid date: $spec" >&2; return 1; }
  printf '\n'
  print_day_table "$day"
  printf '\n'
  filter_entries "$day"
  local i
  for i in "${FILTERED[@]+"${FILTERED[@]}"}"; do
    print_entry_card "$i"
    printf '\n'
  done
}

cmd_search() {
  load_db
  local q="${*:-}"
  if [[ -z "$q" ]]; then
    if [[ -t 0 ]]; then
      q="$(ask_line "  Search item, ingredient, or note: " "")"
    else
      echo "Usage: foodgram.sh search <text>" >&2
      return 2
    fi
  fi
  q="$(lc "$(trim "$q")")"
  [[ -n "$q" ]] || { echo "Empty search." >&2; return 1; }

  local i hay n=0
  printf '\n  %sSearch:%s %s\n\n' "$B" "$R" "$q"
  for i in "${!IDS[@]}"; do
    hay="$(lc "${ITEMS[$i]} ${INGS[$i]} ${NOTES[$i]} ${MEALS[$i]} ${KINDS[$i]}")"
    if [[ "$hay" == *"$q"* ]]; then
      print_entry_card "$i"
      printf '\n'
      n=$((n + 1))
    fi
  done
  if (( n == 0 )); then
    printf '  %sNo matches.%s\n\n' "$cDIM" "$R"
  else
    printf '  %s%d match(es)%s\n\n' "$cDIM" "$n" "$R"
  fi
}

browse_day() {
  load_db
  local day
  day="$(resolve_date "${1:-today}")" || day="$(today)"

  while true; do
    cls
    banner
    printf '  %s< p  previous day          n  next day  >%s\n\n' "$cDIM" "$R"
    print_day_table "$day"
    filter_entries "$day"
    printf '\n'
    local i
    for i in "${FILTERED[@]+"${FILTERED[@]}"}"; do
      print_entry_card "$i"
      printf '\n'
    done
    printf '  %s[A]%sdd   %s[E]%sdit   %s[D]%selete   %s[C]%sopy to another time\n' \
      "$cORG" "$R" "$cORG" "$R" "$cORG" "$R" "$cORG" "$R"
    printf '  %s[R]%seport this day    %s[G]%soto date    %s[B]%sack\n\n' \
      "$cORG" "$R" "$cORG" "$R" "$cORG" "$R"
    local key
    key="$(ask_line "  Choice: " "")"
    case "$(lc "$key")" in
      ""|b|q|back) return 0 ;;
      p|prev|-)
        day="$(date -d "$day - 1 day" +%F)"
        ;;
      n|next|+)
        day="$(date -d "$day + 1 day" +%F)"
        ;;
      g|goto)
        local nd
        nd="$(ask_line "  Go to date: " "$day")"
        if nd="$(resolve_date "$nd")"; then
          day="$nd"
        else
          pause "Invalid date. "
        fi
        ;;
      a|add)
        cmd_add --date "$day"
        load_db
        pause
        ;;
      e|edit)
        cmd_edit "$day"
        load_db
        pause
        ;;
      d|del|delete)
        cmd_delete "$day"
        load_db
        pause
        ;;
      c|copy)
        filter_entries "$day"
        if (( ${#FILTERED[@]} == 0 )); then
          pause "Nothing to copy. "
          continue
        fi
        local pick src dest dest_t
        pick="$(ask_line "  Copy which # (list number or id): " "")"
        if src="$(filtered_pick "$pick")"; then
          src="${IDS[$src]}"
        elif [[ "$pick" =~ ^[0-9]+$ ]] && src="$(index_of_id "$pick")"; then
          src="${IDS[$src]}"
        else
          pause "Invalid selection. "
          continue
        fi
        dest="$(ask_line "  Copy onto date: " "$(today)")"
        dest_t="$(ask_line "  Time: " "$(date +%H:%M)")"
        cmd_copy "$src" "$dest" "$dest_t"
        load_db
        pause
        ;;
      r|report)
        local out
        out="$REPORT_DIR/${APP_SHORT}-$day.txt"
        generate_report "$day" "$day" 0 > "$out"
        printf '\n  Wrote %s\n' "$out"
        open_report "$out"
        pause
        ;;
      *)
        pause "Unknown choice. "
        ;;
    esac
  done
}

# =============================================================================
#  Reports — US Letter, 72-column plain text
# =============================================================================

# Flowing left-aligned text: readable in a text editor and in Word/LibreOffice
# with any font. Horizontal rules are 72 characters for Letter + ~1" margins
# at 12-pt Courier (or wrap naturally in a proportional face).
report_header() {
  local title="$1" period="$2"
  local prepared
  prepared="$(date +"%A, %B %-d, %Y at %-I:%M %p")"
  printf '%s\n' "$APP_NAME"
  printf '%s\n' "Daily Food & Drink Journal"
  hr "="
  wrap "Report:    $title" "$REPORT_WIDTH"
  wrap "Period:    $period" "$REPORT_WIDTH"
  wrap "Prepared:  $prepared" "$REPORT_WIDTH"
  wrap "Paper:     US Letter (8.5 x 11 in)  ·  ${REPORT_WIDTH}-column text" "$REPORT_WIDTH"
  printf '\n'
  wrap "Tip: open this file in a text editor to print as-is, or in a word processor with Courier New / Liberation Mono 11 pt, US Letter, 0.75–1 in margins." "$REPORT_WIDTH"
  printf '\n'
  hr "="
  printf '\n'
}

emit_entry_block() {
  local i="$1"
  local when item kind qty ing notes piece
  when="$(fmt_time_12 "${TIMES[$i]}")"
  item="${ITEMS[$i]}"
  kind="${KINDS[$i]}"
  qty="${QTYS[$i]}"
  ing="${INGS[$i]}"
  notes="${NOTES[$i]}"

  wrap "${when}  —  ${item}  (${kind})" "$REPORT_WIDTH"
  [[ -n "$qty" ]] && wrap "Serving: ${qty}" "$REPORT_WIDTH"
  if [[ -n "$ing" ]]; then
    printf 'Ingredients:\n'
    split_ingredients "$ing"
    if (( ${#ING_PARTS[@]} == 0 )); then
      wrap "  $ing" "$REPORT_WIDTH"
    else
      for piece in "${ING_PARTS[@]}"; do
        wrap "  - $piece" "$REPORT_WIDTH"
      done
    fi
  fi
  if [[ -n "$notes" ]]; then
    wrap "Notes: ${notes}" "$REPORT_WIDTH"
  fi
  printf '\n'
}

# from, to, page_breaks (0/1) — writes the report to stdout.
generate_report() {
  local from="$1" to="$2" page_breaks="${3:-0}"
  load_db
  entries_in_range "$from" "$to"

  local title period
  if [[ "$from" == "$to" ]]; then
    title="Daily log"
    period="$(fmt_date_long "$from")"
  else
    title="Period log"
    period="$(fmt_date_long "$from")  through  $(fmt_date_long "$to")"
  fi
  report_header "$title" "$period"

  if (( ${#FILTERED[@]} == 0 )); then
    printf 'No entries in this period.\n'
    printf '\n'
    hr "="
    printf '%s\n' "$APP_CREDIT"
    return 0
  fi

  local meal_order=(breakfast lunch dinner snack other)
  local foods=0 drinks=0
  local last_date="" i meal first_day=1
  local -A item_seen_food=() item_seen_drink=()
  local -A item_days_food=() item_days_drink=()

  # Walk dates in order; for each date emit meal sections.
  local dates_in=() d last_d=""
  for i in "${FILTERED[@]}"; do
    d="${DATES[$i]}"
    if [[ "$d" != "$last_d" ]]; then
      dates_in+=("$d")
      last_d="$d"
    fi
  done

  for d in "${dates_in[@]}"; do
    if [[ "$from" != "$to" ]]; then
      if (( first_day == 0 && page_breaks == 1 )); then
        printf '\f'
      fi
      if (( first_day == 0 )); then
        hr "-"
        printf '\n'
      fi
      printf '%s\n' "$(fmt_date_long "$d")"
      hr "-"
      printf '\n'
    fi
    first_day=0

    local m any
    for m in "${meal_order[@]}"; do
      any=0
      for i in "${FILTERED[@]}"; do
        [[ "${DATES[$i]}" == "$d" && "${MEALS[$i]}" == "$m" ]] || continue
        if (( any == 0 )); then
          printf '%s\n' "$(meal_title "$m")"
          hr "-"
          any=1
        fi
        emit_entry_block "$i"
        if [[ "${KINDS[$i]}" == drink ]]; then
          drinks=$((drinks + 1))
          item_seen_drink["${ITEMS[$i]}"]=1
          if [[ "${item_days_drink["${ITEMS[$i]}"]-}" != *"$d"* ]]; then
            item_days_drink["${ITEMS[$i]}"]+="${item_days_drink["${ITEMS[$i]}"]:+, }$d"
          fi
        else
          foods=$((foods + 1))
          item_seen_food["${ITEMS[$i]}"]=1
          if [[ "${item_days_food["${ITEMS[$i]}"]-}" != *"$d"* ]]; then
            item_days_food["${ITEMS[$i]}"]+="${item_days_food["${ITEMS[$i]}"]:+, }$d"
          fi
        fi
      done
    done
  done

  hr "="
  printf '\n'
  printf 'TOTALS\n'
  hr "-"
  printf 'Entries:  %d     Foods: %d     Drinks: %d\n' \
    "${#FILTERED[@]}" "$foods" "$drinks"
  printf 'Days:     %d     (%s to %s)\n' "${#dates_in[@]}" "$from" "$to"
  printf '\n'

  if [[ "$from" != "$to" ]]; then
    printf 'INDEX OF ITEMS\n'
    hr "-"
    local name
    if (( ${#item_seen_food[@]} > 0 )); then
      printf 'Foods\n'
      while IFS= read -r name; do
        [[ -z "$name" ]] && continue
        wrap "  - $name  (${item_days_food[$name]})" "$REPORT_WIDTH"
      done < <(printf '%s\n' "${!item_seen_food[@]}" | sort -f)
      printf '\n'
    fi
    if (( ${#item_seen_drink[@]} > 0 )); then
      printf 'Drinks\n'
      while IFS= read -r name; do
        [[ -z "$name" ]] && continue
        wrap "  - $name  (${item_days_drink[$name]})" "$REPORT_WIDTH"
      done < <(printf '%s\n' "${!item_seen_drink[@]}" | sort -f)
      printf '\n'
    fi
  fi

  hr "="
  printf '%s\n' "$APP_CREDIT"
}

open_report() {
  local file="$1"
  [[ -f "$file" ]] || return 1
  printf '  Report file:\n    %s\n' "$file"
  if [[ ! -t 0 ]]; then
    return 0
  fi
  local ed="${FOODGRAM_EDITOR:-${VISUAL:-${EDITOR-}}}"
  if [[ -n "$ed" ]]; then
    if confirm "Open in editor ($ed)?"; then
      # shellcheck disable=SC2086
      $ed "$file" || true
      return 0
    fi
  fi
  if have_cmd xdg-open && confirm "Open with the default application?"; then
    xdg-open "$file" >/dev/null 2>&1 || true
  fi
}

cmd_report() {
  local from="" to="" out="" page_breaks=0 do_open=0 to_stdout=0
  local want_week=0 want_month=0 want_today=0

  while [[ $# -gt 0 ]]; do
    case "$1" in
      -d|--date)         from="${2-}"; to="${2-}"; shift 2 ;;
      -f|--from)         from="${2-}"; shift 2 ;;
      -t|--to)           to="${2-}"; shift 2 ;;
      -o|--output|--file) out="${2-}"; shift 2 ;;
      -w|--width)        REPORT_WIDTH="${2-}"; shift 2 ;;
      --week)            want_week=1; shift ;;
      --month)           want_month=1; shift ;;
      --today)           want_today=1; shift ;;
      --page-breaks)     page_breaks=1; shift ;;
      --open)            do_open=1; shift ;;
      --stdout)          to_stdout=1; shift ;;
      -h|--help)
        cat <<'EOF'
Usage: foodgram.sh report [options]

  -d, --date DATE         Single day (today, yesterday, YYYY-MM-DD, ...)
  -f, --from DATE         Range start
  -t, --to DATE           Range end (default: today)
      --today             Today only
      --week              Last 7 days (including today)
      --month             Current calendar month
  -o, --output FILE       Write to FILE (default: data/reports/...)
      --stdout            Print to the terminal only
      --page-breaks       Form-feed between days (some printers / editors)
  -w, --width N           Wrap width (default 72, US Letter)
      --open              Open the file after writing

The report is plain UTF-8 text. Open it in any text editor or word
processor and print. Use a monospaced font (Courier New, 11 pt) and
US Letter paper for a tidy page.

Examples:
  foodgram.sh report
  foodgram.sh report --date yesterday
  foodgram.sh report --week --open
  foodgram.sh report --from 2026-08-01 --to 2026-08-14 -o august.txt
EOF
        return 0
        ;;
      *)
        # Bare date word
        if [[ -z "$from" ]]; then
          from="$1"; to="$1"; shift
        else
          echo "Unknown argument: $1" >&2
          return 2
        fi
        ;;
    esac
  done

  if (( want_today )); then
    from="$(today)"; to="$(today)"
  elif (( want_week )); then
    from="$(date -d '6 days ago' +%F)"
    to="$(today)"
  elif (( want_month )); then
    from="$(date +%Y-%m-01)"
    to="$(today)"
  fi

  if [[ -z "$from" && -t 0 ]]; then
    printf '\n  %sPrintable report%s\n\n' "$B" "$R"
    printf '  [1] Today\n'
    printf '  [2] A specific day\n'
    printf '  [3] Last 7 days\n'
    printf '  [4] This calendar month\n'
    printf '  [5] Custom date range\n'
    local choice
    choice="$(ask_line "  Choice: " "1")"
    case "$choice" in
      2)
        from="$(ask_line "  Date: " "$(today)")"
        to="$from"
        ;;
      3)
        from="$(date -d '6 days ago' +%F)"
        to="$(today)"
        ;;
      4)
        from="$(date +%Y-%m-01)"
        to="$(today)"
        ;;
      5)
        from="$(ask_line "  From: " "$(date +%Y-%m-01)")"
        to="$(ask_line "  To: " "$(today)")"
        ;;
      *)
        from="$(today)"; to="$(today)"
        ;;
    esac
  fi

  [[ -z "$from" ]] && from="$(today)"
  [[ -z "$to" ]] && to="$from"
  from="$(resolve_date "$from")" || { echo "Invalid from date." >&2; return 1; }
  to="$(resolve_date "$to")" || { echo "Invalid to date." >&2; return 1; }
  if [[ "$from" > "$to" ]]; then
    local tmp="$from"; from="$to"; to="$tmp"
  fi

  if (( to_stdout )); then
    generate_report "$from" "$to" "$page_breaks"
    return 0
  fi

  if [[ -z "$out" ]]; then
    if [[ "$from" == "$to" ]]; then
      out="$REPORT_DIR/${APP_SHORT}-$from.txt"
    else
      out="$REPORT_DIR/${APP_SHORT}-${from}_to_${to}.txt"
    fi
  fi

  # Allow "-" for stdout
  if [[ "$out" == "-" ]]; then
    generate_report "$from" "$to" "$page_breaks"
    return 0
  fi

  mkdir -p "$(dirname "$out")"
  generate_report "$from" "$to" "$page_breaks" > "$out"
  printf '  Wrote report:\n    %s\n\n' "$out"

  if (( do_open )); then
    local ed="${FOODGRAM_EDITOR:-${VISUAL:-${EDITOR:-xdg-open}}}"
    # shellcheck disable=SC2086
    $ed "$out" || true
  elif [[ -t 0 ]]; then
    if confirm "Print the report on screen now?"; then
      printf '\n'
      cat "$out"
      printf '\n'
    fi
    open_report "$out"
  fi
}

# =============================================================================
#  Interactive menu
# =============================================================================

menu_loop() {
  while true; do
    cls
    banner
    load_db
    local n="${#IDS[@]}"
    printf '  Journal: %s%d%s entr%s   data: %s\n\n' \
      "$cGRN" "$n" "$R" "$( (( n==1 )) && echo y || echo ies )" "$DATA_DIR"

    printf '  %s[A]%s  Add food or drink     (any date / time)\n' "$cORG" "$R"
    printf '  %s[T]%s  Today\n' "$cORG" "$R"
    printf '  %s[V]%s  View / edit a day     (add to past days here too)\n' "$cORG" "$R"
    printf '  %s[E]%s  Edit an entry by #\n' "$cORG" "$R"
    printf '  %s[S]%s  Search  (name, ingredient, note)\n' "$cORG" "$R"
    printf '  %s[R]%s  Printable report\n' "$cORG" "$R"
    printf '  %s[L]%s  List everything\n' "$cORG" "$R"
    printf '  %s[H]%s  Help\n' "$cORG" "$R"
    printf '  %s[Q]%s  Quit\n\n' "$cORG" "$R"

    local key
    key="$(ask_line "  Choice: " "")"
    case "$(lc "$key")" in
      a|add)
        cmd_add
        if [[ -t 0 ]] && confirm "Add another?"; then
          continue
        fi
        pause
        ;;
      t|today)
        browse_day "$(today)"
        ;;
      v|view|day)
        local d
        d="$(ask_line "  Which day? " "$(today)")"
        browse_day "$d"
        ;;
      e|edit)
        cmd_edit
        pause
        ;;
      d|del|delete)
        cmd_delete
        pause
        ;;
      s|search|/)
        cmd_search
        pause
        ;;
      r|report|print)
        cmd_report
        pause
        ;;
      l|list|all)
        cmd_list all
        pause
        ;;
      h|help|?)
        usage
        pause
        ;;
      q|quit|exit|x)
        printf '\n  %s\n\n' "$APP_CREDIT"
        return 0
        ;;
      *)
        pause "Unknown choice. "
        ;;
    esac
  done
}

usage() {
  cat <<EOF
$APP_NAME v$VERSION
Daily food & drink journal

USAGE
  foodgram.sh                      Interactive menu
  foodgram.sh add [options] [item]
  foodgram.sh edit  [id|date]
  foodgram.sh delete [id|date]
  foodgram.sh copy <id> [date] [time]
  foodgram.sh list [date|all|week]
  foodgram.sh today
  foodgram.sh search <text>
  foodgram.sh report [options]
  foodgram.sh help

ADD (any calendar day or clock time)
  -d, --date DATE        today / yesterday / YYYY-MM-DD / "3 days ago"
  -t, --time HH:MM
  -k, --kind food|drink
  -m, --meal breakfast|lunch|dinner|snack|other
  -i, --item NAME
  -q, --qty TEXT
  -g, --ingredients TEXT
  -n, --notes TEXT

REPORT (plain text, US Letter)
  foodgram.sh report --today
  foodgram.sh report --week --open
  foodgram.sh report --from 2026-08-01 --to 2026-08-14
  foodgram.sh report --date yesterday -o ~/yesterday.txt

  Reports are 72-column UTF-8 text. Open the file in a text editor or
  word processor and print. Suggested: Courier New 11 pt, US Letter,
  0.75–1 inch margins. Files land in:
    $REPORT_DIR

DATA
  Entries:  $DB_FILE
  Override the data directory with FOODGRAM_HOME.

EXAMPLES
  foodgram.sh add -k drink -m breakfast -g "coffee, milk" Coffee
  foodgram.sh add --date yesterday --time 19:10 "Leftover stew"
  foodgram.sh edit 12
  foodgram.sh search peanut
  foodgram.sh report --week
EOF
}

# =============================================================================
#  Main
# =============================================================================

main() {
  ensure_dirs
  local cmd="${1:-}"
  if [[ -n "$cmd" ]]; then
    shift
  fi
  case "$cmd" in
    ""|menu|tui|ui)          menu_loop ;;
    add|a)                   cmd_add "$@" ;;
    edit|e)                  cmd_edit "$@" ;;
    delete|del|rm|remove)    cmd_delete "$@" ;;
    copy|cp|repeat)          cmd_copy "$@" ;;
    list|ls)                 cmd_list "$@" ;;
    today)                   cmd_list today ;;
    search|find|grep)        cmd_search "$@" ;;
    report|print|export)     cmd_report "$@" ;;
    view|browse|day)         browse_day "${1:-today}" ;;
    help|-h|--help)          usage ;;
    version|-V|--version)    printf '%s %s\n' "$APP_NAME" "$VERSION" ;;
    *)
      echo "Unknown command: $cmd" >&2
      echo "Try: foodgram.sh help" >&2
      return 2
      ;;
  esac
}

main "$@"
