#!/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 GROK CLI - xAI Interface
# Wrapper for Grok API access from the Round Table
# ═══════════════════════════════════════════════════════════════════════════════

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

# Config
API_KEY="${XAI_API_KEY:-}"
MODEL="${GROK_MODEL:-grok-beta}"
API_URL="https://api.x.ai/v1/chat/completions"
HISTORY_FILE="$HOME/.blackroad/roundtable/agents/grok_history.jsonl"

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

# Check API key
if [[ -z "$API_KEY" ]]; then
    echo -e "${RED}Error: XAI_API_KEY not set${RESET}"
    echo ""
    echo "To set up Grok access:"
    echo "  1. Go to https://console.x.ai/"
    echo "  2. Create an API key"
    echo "  3. Add to ~/.zshrc:"
    echo "     export XAI_API_KEY='your-key-here'"
    echo ""
    # Check if key file exists
    if [[ -f "$HOME/.xai_keys" ]]; then
        echo -e "${AMBER}Found ~/.xai_keys - attempting to load...${RESET}"
        source "$HOME/.xai_keys"
        API_KEY="${XAI_API_KEY:-}"
    fi
    if [[ -z "$API_KEY" ]]; then
        exit 1
    fi
fi

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

# Send message to Grok
send_message() {
    local message="$1"
    local system_prompt="${2:-You are Grok, part of the BlackRoad AI Round Table. You work alongside Claude, Copilot, Codex, and Gemini. Be witty, direct, and technically sharp. Do not be afraid to be edgy.}"

    # Build request JSON (safe construction via jq)
    local request_json
    request_json=$(jq -n \
      --arg model "$MODEL" \
      --arg sys "$system_prompt" \
      --arg msg "$message" \
      '{model: $model, messages: [{role: "system", content: $sys}, {role: "user", content: $msg}], temperature: 0.8, max_tokens: 2048}')

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

    # Extract text from response
    local text=$(echo "$response" | jq -r '.choices[0].message.content // .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 "${RED}Grok CLI ready. Type 'exit' to quit.${RESET}"
    echo -e "${WHITE}(Warning: Grok may be brutally honest)${RESET}"
    echo ""

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

        if [[ "$input" == "exit" ]] || [[ "$input" == "quit" ]]; then
            echo -e "${RED}Later, human.${RESET}"
            break
        fi

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

        echo ""
        echo -e "${RED}Grok:${RESET}"
        send_message "$input"
        echo ""
    done
}

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

# Help
show_help() {
    show_banner
    echo "Usage: grok-cli [options] [message]"
    echo ""
    echo "Options:"
    echo "  -i, --interactive    Start interactive mode"
    echo "  -m, --model MODEL    Use specific model (default: grok-beta)"
    echo "  -h, --help           Show this help"
    echo ""
    echo "Examples:"
    echo "  grok-cli 'Roast my code'"
    echo "  grok-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
