#!/bin/bash

# Optional: Load external defaults and functions
[ -f ~/lbin/sh.defaults ] && . ~/lbin/sh.defaults
[ -f ~/lbin/sh.functions ] && . ~/lbin/sh.functions
[ -f ~/lbin/tipsFunctions.sh ] && . ~/lbin/tipsFunctions.sh

#echo "dataFile=$dataFile";
#echo "dataDir=$dataDir";
# Set default paths if not already defined
dataDir="${dataDir:-$HOME/lbin}"
dataFile="${dataFile:-$dataDir/dataFiles/tips.csv}"
dataFile="${dataFile:-$HOME/lbin/dataFiles/tips.csv}"

echo "dataFile=$dataFile"
helpFile="${helpFile:-$dataDir/dataFiles/tipsHelp.txt}"
attachDir="${attachDir:-$dataDir/tipsAttachments}"
reportFile="${reportFile:-$dataDir/tipsReport.awk}"
printAWK="${printAWK:-$dataDir/tipsPrint.awk}"
summaryAWK="${summaryAWK:-$dataDir/tipsSummary.awk}"
csvDelim="${csvDelim:-<>}"

use_less=0  # Default: DO NOT use less unless -P is passed


show_help() {
  cat <<EOF
Usage: $0 [options]

Options:
  -a        Add new record
  -c        Convert CSV to JSON
  -d        Debug mode
  -e FILE   Edit attachment
  -E        Edit data file
  -f TERM   Fuzzy search (regex)
  -g TAG    Filter by tag
  -G TERM   Summary search (vertical)
  -h        Show help
  -L        Disable pager (less)
  -o TERM   Open link in browser
  -r        Show all records (vertical)
  -R        Run report
  -s TERM   Search records (vertical)
  -S        Show summary of all records (vertical)
  -t N      Tail last N records
  -T TERM   Title-only search
  -C CAT    Filter by category
  -u        Update record (TODO)
  -x        Exact match search (TODO)
	-J        Convert CSV to JSON
  -Y        Convert CSV to YAML
EOF
  [ -f "$helpFile" ] && cat "$helpFile"
}

# Parse command-line options
	while getopts "aAcdEe:ho:rRs:t:T:uvx:C:g:G:Sf:PLYJ" opt; do
  case $opt in
    a|A) add_record ;;
    c) convert_to_json ;;
    d) set -x ;;
    e) edit_attachment "$OPTARG" ;;
    E) edit_datafile ;;
    h) show_help ;;
    o|w) getHTML "$OPTARG" ;;  # Assuming getHTML is defined in sh.functions
    r) show_all_records ;;
    R) generate_report ;;
    s) search_records "$OPTARG" ;;
    t) tail_records "$OPTARG" ;;
		v) validate_records ;;
    T) title_only_search "$OPTARG" ;;
    C) filter_by_category "$OPTARG" ;;
    g) filter_by_tag "$OPTARG" ;;
    G) summary_search "$OPTARG" ;;
    S) show_summary ;;
    f) fuzzy_search "$OPTARG" ;;
    L) use_less=0 ;;
    u) update_record ;;
		Y) convert_to_yaml ;;
    J) convert_to_json ;;
    x) exact_match_search ;;
    *) echo "❌ Invalid option"; show_help; exit 1 ;;
  esac
done

