#!/usr/bin/env bash
# ============================================================================
# BLACKROAD OS, INC. - PROPRIETARY AND CONFIDENTIAL
# Copyright (c) 2025-2026 BlackRoad OS, Inc. All Rights Reserved.
# 
# This code is the intellectual property of BlackRoad OS, Inc.
# AI-assisted development does not transfer ownership to AI providers.
# Unauthorized use, copying, or distribution is prohibited.
# NOT licensed for AI training or data extraction.
# ============================================================================
# ═══════════════════════════════════════════════════════════════════════════════
# BLACKROAD GEMINI CLI - Google AI Interface
# Wrapper for Gemini API access from the Round Table
# ═══════════════════════════════════════════════════════════════════════════════

# Colors
GREEN='\033[38;5;82m'
AMBER='\033[38;5;214m'
RED='\033[38;5;196m'
RESET='\033[0m'
BOLD='\033[1m'

# Config
API_KEY="${GOOGLE_AI_API_KEY:-${GEMINI_API_KEY:-}}"
MODEL="${GEMINI_MODEL:-gemini-1.5-pro}"
API_URL="https://generativelanguage.googleapis.com/v1beta/models/${MODEL}:generateContent"
HISTORY_FILE="$HOME/.blackroad/roundtable/agents/gemini_history.jsonl"

# Ensure history directory exists
mkdir -p "$(dirname "$HISTORY_FILE")"

# Check API key
if [[ -z "$API_KEY" ]]; then
    echo -e "${RED}Error: GOOGLE_AI_API_KEY or GEMINI_API_KEY not set${RESET}"
    echo ""
    echo "To set up Gemini access:"
    echo "  1. Go to https://aistudio.google.com/apikey"
    echo "  2. Create an API key"
    echo "  3. Add to ~/.zshrc:"
    echo "     export GOOGLE_AI_API_KEY='your-key-here'"
    echo ""
    exit 1
fi

# Banner
show_banner() {
    echo -e "${GREEN}${BOLD}"
    cat << 'EOF'
    ╔════════════════════════════════════════╗
    ║   ██████╗ ███████╗███╗   ███╗██╗███╗   ██║
    ║  ██╔════╝ ██╔════╝████╗ ████║██║████╗  ██║
    ║  ██║  ███╗█████╗  ██╔████╔██║██║██╔██╗ ██║
    ║  ██║   ██║██╔══╝  ██║╚██╔╝██║██║██║╚██╗██║
    ║  ╚██████╔╝███████╗██║ ╚═╝ ██║██║██║ ╚████║
    ║   ╚═════╝ ╚══════╝╚═╝     ╚═╝╚═╝╚═╝  ╚═══╝
    ╚════════════════════════════════════════╝
EOF
    echo -e "${RESET}"
    echo -e "    ${AMBER}BlackRoad Round Table - Google AI${RESET}"
    echo -e "    Model: ${GREEN}$MODEL${RESET}"
    echo ""
}

# Send message to Gemini
send_message() {
    local message="$1"
    local system_prompt="${2:-You are Gemini, part of the BlackRoad AI Round Table. You work alongside Claude, Copilot, Codex, and Grok. Be concise and technical.}"

    # Build request JSON (safe construction via jq)
    local request_json
    request_json=$(jq -n \
      --arg text "$system_prompt\n\nUser: $message" \
      '{contents: [{parts: [{text: $text}]}], generationConfig: {temperature: 0.7, maxOutputTokens: 2048}}')

    # Make API call
    local response=$(curl -s -X POST "$API_URL?key=$API_KEY" \
        -H "Content-Type: application/json" \
        -d "$request_json")

    # Extract text from response
    local text=$(echo "$response" | jq -r '.candidates[0].content.parts[0].text // .error.message // "Error: No response"')

    # Log to history (safe JSON via jq)
    jq -nc --arg ts "$(date -Iseconds)" --arg c "$message" '{timestamp: $ts, role: "user", content: $c}' >> "$HISTORY_FILE"
    jq -nc --arg ts "$(date -Iseconds)" --arg c "$text" '{timestamp: $ts, role: "assistant", content: $c}' >> "$HISTORY_FILE"

    echo "$text"
}

# Interactive mode
interactive_mode() {
    show_banner
    echo -e "${GREEN}Gemini CLI ready. Type 'exit' to quit.${RESET}"
    echo ""

    while true; do
        echo -ne "${AMBER}gemini>${RESET} "
        read -r input

        if [[ "$input" == "exit" ]] || [[ "$input" == "quit" ]]; then
            echo -e "${GREEN}Goodbye from Gemini!${RESET}"
            break
        fi

        if [[ -z "$input" ]]; then
            continue
        fi

        echo ""
        echo -e "${GREEN}Gemini:${RESET}"
        send_message "$input"
        echo ""
    done
}

# One-shot mode
oneshot_mode() {
    local message="$*"
    send_message "$message"
}

# Help
show_help() {
    show_banner
    echo "Usage: gemini-cli [options] [message]"
    echo ""
    echo "Options:"
    echo "  -i, --interactive    Start interactive mode"
    echo "  -m, --model MODEL    Use specific model (default: gemini-1.5-pro)"
    echo "  -h, --help           Show this help"
    echo ""
    echo "Examples:"
    echo "  gemini-cli 'What is quantum computing?'"
    echo "  gemini-cli -i"
    echo ""
}

# Main
case "${1:-}" in
    -h|--help|help)
        show_help
        ;;
    -i|--interactive)
        interactive_mode
        ;;
    -m|--model)
        MODEL="$2"
        shift 2
        if [[ -n "$*" ]]; then
            oneshot_mode "$@"
        else
            interactive_mode
        fi
        ;;
    "")
        interactive_mode
        ;;
    *)
        oneshot_mode "$@"
        ;;
esac
