#!/usr/bin/env bash
# ask_gemini.sh — Submit a question to Gemini CLI (non-interactive).
#
# Usage:
#   ask_gemini.sh "question"
#   ask_gemini.sh -q question_file.md
#   ask_gemini.sh -f context.java -f diagram.png "question"
#
# Options:
#   -f FILE     Attach a context file (repeatable).
#               Text files (.java .c .py .md .txt .xml etc.) are embedded inline.
#               Binary/multimodal files (.png .jpg .pdf .gif) use Gemini @ reference.
#   -q FILE     Read question text from a file.
#   -m MODEL    Model override. Accepts short names:
#                 flash (default) → gemini-2.5-flash
#                 pro             → gemini-2.5-pro
#               or full model IDs like gemini-2.0-flash.
#   -o FILE     Write response to FILE in addition to stdout.
#   -h          Show this help.
#
# Environment:
#   GEMINI_API_KEY   Required — set in ~/.bashrc.
#   GEMINI_BIN       Override path to gemini binary.

set -euo pipefail

# ── Locate binary ─────────────────────────────────────────────────────────────

GEMINI_BIN="${GEMINI_BIN:-}"
if [[ -z "$GEMINI_BIN" ]]; then
  if command -v gemini &>/dev/null; then
    GEMINI_BIN="$(command -v gemini)"
  else
    # Try nvm-installed path
    NVM_GEMINI="$(ls ~/.nvm/versions/node/*/bin/gemini 2>/dev/null | tail -1 || true)"
    [[ -n "$NVM_GEMINI" ]] && GEMINI_BIN="$NVM_GEMINI"
  fi
fi
[[ -n "$GEMINI_BIN" ]] || { echo "ERROR: gemini not found. Run: npm install -g @google/gemini-cli" >&2; exit 1; }

# ── Defaults ──────────────────────────────────────────────────────────────────

DEFAULT_MODEL="gemini-2.5-flash"
CONTEXT_FILES=()
QUESTION=""
QUESTION_FILE=""
MODEL=""
OUTPUT_FILE=""

# ── Parse args ────────────────────────────────────────────────────────────────

while getopts "f:q:m:o:h" opt; do
  case "$opt" in
    f) CONTEXT_FILES+=("$OPTARG") ;;
    q) QUESTION_FILE="$OPTARG" ;;
    m) MODEL="$OPTARG" ;;
    o) OUTPUT_FILE="$OPTARG" ;;
    h) awk 'NR==1{next} /^#/{gsub(/^# ?/,""); print; next} {exit}' "$0"; exit 0 ;;
    *) echo "Unknown flag: -$OPTARG" >&2; exit 1 ;;
  esac
done
shift $((OPTIND - 1))

# ── Question ──────────────────────────────────────────────────────────────────

if [[ -n "$QUESTION_FILE" ]]; then
  [[ -f "$QUESTION_FILE" ]] || { echo "ERROR: question file not found: $QUESTION_FILE" >&2; exit 1; }
  QUESTION="$(cat "$QUESTION_FILE")"
elif [[ $# -gt 0 ]]; then
  QUESTION="$*"
else
  echo "ERROR: provide a question via -q FILE or as a positional argument." >&2
  exit 1
fi

# ── Resolve model ─────────────────────────────────────────────────────────────

case "${MODEL:-flash}" in
  flash)          MODEL="gemini-2.5-flash" ;;
  pro)            MODEL="gemini-2.5-pro" ;;
  flash-2.0)      MODEL="gemini-2.0-flash" ;;
  *)              : ;;   # pass through full model IDs unchanged
esac

# ── Build prompt ──────────────────────────────────────────────────────────────
# Text files → inline.  Binary/multimodal → @path reference in prompt.

MULTIMODAL_EXTS="png jpg jpeg gif pdf bmp tiff tif webp"

PROMPT="$QUESTION"
MULTIMODAL_REFS=""

for f in "${CONTEXT_FILES[@]}"; do
  if [[ ! -f "$f" ]]; then
    echo "WARNING: context file not found: $f" >&2
    continue
  fi
  ext="${f##*.}"
  ext="${ext,,}"   # lowercase
  is_binary=0
  for e in $MULTIMODAL_EXTS; do
    [[ "$ext" == "$e" ]] && { is_binary=1; break; }
  done
  if [[ $is_binary -eq 1 ]]; then
    MULTIMODAL_REFS+=" @${f}"
  else
    PROMPT+=$'\n\n'"--- FILE: $f ---"$'\n'"$(cat "$f")"$'\n'"--- END FILE ---"
  fi
done

# Prepend any @-references to the prompt text
if [[ -n "$MULTIMODAL_REFS" ]]; then
  PROMPT="${MULTIMODAL_REFS} ${PROMPT}"
fi

# ── Invoke Gemini ─────────────────────────────────────────────────────────────

if [[ -n "$OUTPUT_FILE" ]]; then
  "$GEMINI_BIN" -m "$MODEL" -p "$PROMPT" 2>&1 | tee "$OUTPUT_FILE"
else
  "$GEMINI_BIN" -m "$MODEL" -p "$PROMPT" 2>&1
fi
