#!/usr/bin/env bash
#
# gemini — ClaudeAll shim that:
#   1. Sources ~/.gemini/.env (and ~/.claude/.env as fallback) so MCP servers
#      see CONTEXT7_API_KEY / EXA_API_KEY / Z_AI_API_KEY / TELEGRAM_* / etc.
#   2. Auto-prepends --yolo (-y) to make Gemini autonomous by default.
#   3. Forwards all args to the REAL gemini binary further down PATH.
#
# Opt out of YOLO for a single run:
#   gemini --no-yolo ...
#   GEMINI_NO_YOLO=1 gemini ...
#
# Bypass this shim entirely:
#   command -v gemini -a       # see all gemini binaries
#   /usr/local/bin/gemini ...  # call the real one directly

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
}
load_env "$HOME/.claude/.env"
load_env "$HOME/.gemini/.env"

# ─── Find the REAL gemini binary (skip ourselves) ─────────────────────────
SELF="$(readlink -f "$0" 2>/dev/null || realpath "$0" 2>/dev/null || echo "$0")"

REAL_GEMINI=""
# Walk PATH manually, skipping the shim itself
IFS=':' read -ra DIRS <<< "$PATH"
for dir in "${DIRS[@]}"; do
    candidate="$dir/gemini"
    [ -x "$candidate" ] || continue
    candidate_real="$(readlink -f "$candidate" 2>/dev/null || realpath "$candidate" 2>/dev/null || echo "$candidate")"
    # Skip if this is the shim itself
    if [ "$candidate_real" = "$SELF" ]; then
        continue
    fi
    REAL_GEMINI="$candidate"
    break
done

if [ -z "$REAL_GEMINI" ]; then
    echo "❌ ClaudeAll gemini shim: real gemini binary not found in PATH." >&2
    echo "   Install: npm install -g @google/gemini-cli" >&2
    echo "   (After install, this shim will auto-locate it.)" >&2
    exit 127
fi

# ─── Decide YOLO flag ─────────────────────────────────────────────────────
USE_YOLO=1
ARGS=()
for a in "$@"; do
    case "$a" in
        --no-yolo)        USE_YOLO=0 ;;
        -y|--yolo)        USE_YOLO=1 ;;
        *)                ARGS+=("$a") ;;
    esac
done
[ -n "${GEMINI_NO_YOLO:-}" ] && USE_YOLO=0

# ─── Exec real gemini ─────────────────────────────────────────────────────
if [ "$USE_YOLO" = "1" ]; then
    exec "$REAL_GEMINI" --yolo "${ARGS[@]}"
else
    exec "$REAL_GEMINI" "${ARGS[@]}"
fi
