#!/usr/bin/env bash
#
# gemini-all — Gemini CLI launcher with ClaudeAll superpowers loaded.
#
# What it does:
#   1. Source ~/.gemini/.env (and ~/.claude/.env as fallback) so MCP servers
#      see your CONTEXT7_API_KEY / EXA_API_KEY / Z_AI_API_KEY / etc.
#   2. Default to YOLO mode (--yolo / -y) for autonomous operation.
#   3. Pass through all args to gemini.
#
# Usage:
#   gemini-all                     # interactive YOLO session
#   gemini-all "your prompt"       # one-shot with prompt
#   gemini-all --no-yolo           # disable auto-approve
#   gemini-all -y -- ...           # explicit YOLO with extra args
#
# Override with env vars:
#   GEMINI_BIN=/path/to/gemini gemini-all
#   GEMINI_NO_YOLO=1 gemini-all      # disable yolo for this run

set -u

# ─── Source env files (most-specific first) ───────────────────────────────
load_env() {
    local f="$1"
    if [ -f "$f" ]; then
        set -a
        # shellcheck disable=SC1090
        . "$f" 2>/dev/null || true
        set +a
    fi
}

# Gemini-specific overrides take precedence over the shared Claude env.
load_env "$HOME/.claude/.env"
load_env "$HOME/.gemini/.env"

# ─── Locate gemini binary ─────────────────────────────────────────────────
GEMINI_CMD="${GEMINI_BIN:-gemini}"
if ! command -v "$GEMINI_CMD" &>/dev/null; then
    echo "❌ gemini CLI not found in PATH." >&2
    echo "   Install: npm install -g @google/gemini-cli" >&2
    echo "   Or set GEMINI_BIN=/path/to/gemini" >&2
    exit 127
fi

# ─── YOLO mode (default ON, opt-out with --no-yolo or GEMINI_NO_YOLO=1) ────
YOLO_FLAG="--yolo"
ARGS=()
for a in "$@"; do
    case "$a" in
        --no-yolo)        YOLO_FLAG="" ;;
        -y|--yolo)        YOLO_FLAG="--yolo" ;;
        *)                ARGS+=("$a") ;;
    esac
done
[ -n "${GEMINI_NO_YOLO:-}" ] && YOLO_FLAG=""

# ─── Show what we loaded (only when verbose) ──────────────────────────────
if [ -n "${GEMINI_ALL_VERBOSE:-}" ]; then
    echo "🤖 gemini-all"
    echo "   Binary:  $(command -v "$GEMINI_CMD")"
    echo "   YOLO:    ${YOLO_FLAG:-OFF}"
    echo "   Env:    $(printenv | grep -cE '^(CONTEXT7|EXA|Z_AI|MINIMAX|TELEGRAM)_') vars loaded"
fi

# ─── Exec ─────────────────────────────────────────────────────────────────
if [ -n "$YOLO_FLAG" ]; then
    exec "$GEMINI_CMD" "$YOLO_FLAG" "${ARGS[@]}"
else
    exec "$GEMINI_CMD" "${ARGS[@]}"
fi
