#!/usr/bin/env bash

# Cross-platform Claude-All Launcher v7.0
# Supports: Linux, Termux, macOS, Windows (Git Bash/WSL)
# Includes Superpowers Library (30 skills + 14 agents)

# Auto-load secrets from ~/.claude/.env if present so MCP servers can pick up
# CONTEXT7_API_KEY, EXA_API_KEY, Z_AI_API_KEY, MINIMAX_API_KEY, TELEGRAM_*, etc.
# Check multiple possible locations (Termux proot may use different HOME paths)
for _env_dir in "$HOME/.claude" "$HOME/.kiro" "$PREFIX/../../home/.claude" "/data/data/com.termux/files/home/.claude"; do
    if [ -f "$_env_dir/.env" ]; then
        set -a
        # shellcheck disable=SC1091
        . "$_env_dir/.env" 2>/dev/null || true
        set +a
        break
    fi
done
unset _env_dir

# CRITICAL: Ensure ANTHROPIC_API_KEY is always set so Claude Code never asks
# for OAuth login. Each provider case will override with the real key+base_url.
# Without this, Claude Code shows "Not logged in · Please run /login" on
# headless servers/Termux that can't open a browser for OAuth.
if [[ -z "$ANTHROPIC_API_KEY" ]]; then
    if [[ -n "$Z_AI_API_KEY" ]]; then
        export ANTHROPIC_API_KEY="$Z_AI_API_KEY"
        export ANTHROPIC_BASE_URL="https://api.z.ai/api/anthropic"
    else
        export ANTHROPIC_API_KEY="sk-placeholder-overridden-by-provider"
    fi
fi

# Skip-permissions flag selection.
# Claude Code refuses --dangerously-skip-permissions when running as root for
# safety. The escape hatch is the IS_SANDBOX=1 environment variable: when set,
# Claude treats the environment as a sandbox (Docker, proot-distro, GitHub
# Actions runner, Termux proot) and ALLOWS --dangerously-skip-permissions to
# actually take effect. We always use --dangerously-skip-permissions and add
# IS_SANDBOX=1 only when running as root, so non-root users see no change.
SKIP_PERMS_FLAG="--dangerously-skip-permissions"
if [ "$(id -u 2>/dev/null || echo 1000)" = "0" ]; then
    export IS_SANDBOX=1
fi

# Platform detection
detect_platform() {
    case "$(uname -s)" in
        Linux*)     echo "Linux";;
        Darwin*)    echo "macOS";;
        CYGWIN*|MINGW*|MSYS*) echo "Windows";;
    esac
}

PLATFORM=$(detect_platform)

# Colors - auto-detect and install if needed
setup_colors() {
    # Ensure tput is available for colors
    if ! command -v tput &> /dev/null; then
        if command -v pkg &> /dev/null && [[ "$PLATFORM" != "Windows" ]]; then
            # Install ncurses-utils silently in background
            pkg install -y ncurses-utils &>/dev/null &
        fi
    fi

    if command -v tput &> /dev/null; then
        GREEN=$(tput setaf 2 2>/dev/null || echo "")
        BLUE=$(tput setaf 4 2>/dev/null || echo "")
        RED=$(tput setaf 1 2>/dev/null || echo "")
        YELLOW=$(tput setaf 3 2>/dev/null || echo "")
        NC=$(tput sgr0 2>/dev/null || echo "")
    else
        # Fallback to plain text
        GREEN=''
        BLUE=''
        RED=''
        YELLOW=''
        NC=''
    fi
}

setup_colors

# Reusable functions for API key management
save_api_key() {
    local api_key="$1"
    local key_file="$2"
    local provider_name="$3"

    if [[ -z "$api_key" ]]; then
        echo -e "${RED}Error: No API key provided for $provider_name${NC}" >&2
        return 1
    fi

    if ! echo "$api_key" > "$key_file" 2>/dev/null; then
        echo -e "${YELLOW}Warning: Could not save $provider_name API key to file${NC}" >&2
        return 1
    fi

    if ! chmod 600 "$key_file" 2>/dev/null; then
        echo -e "${YELLOW}Warning: Could not set secure permissions on $provider_name API key file${NC}" >&2
        return 1
    fi

    echo -e "${GREEN}✓ $provider_name API key saved securely${NC}"
    return 0
}

load_api_key() {
    local key_file="$1"
    local provider_name="$2"

    if [[ -f "$key_file" ]]; then
        local saved_key
        saved_key=$(cat "$key_file" 2>/dev/null || echo "")
        if [[ -n "$saved_key" ]]; then
            echo -e "${GREEN}✓ Using saved $provider_name API key${NC}"
            echo "$saved_key"
            return 0
        fi
    fi
    return 1
}

prompt_api_key() {
    local provider_name="$1"
    local api_key=""

    echo -e "${BLUE}Enter $provider_name API Key:${NC}"

    # Check if we're on Windows (no silent input)
    if [[ "$PLATFORM" == "Windows" ]]; then
        read -p "API Key: " api_key
    else
        # Linux/macOS/Termux - silent read
        read -s -p "API Key: " api_key
    fi
    echo ""

    echo "$api_key"
}

# Portable home directory
if [[ -n "$HOME" ]]; then
    USER_HOME="$HOME"
elif [[ -n "$USERPROFILE" ]]; then
    # Windows
    USER_HOME="$USERPROFILE"
else
    USER_HOME="$HOME"
fi

# API Key Files - Use user home directory
GLM_API_KEY_FILE="$USER_HOME/.glm_api_key"
MINIMAX_API_KEY_FILE="$USER_HOME/.minimax_api_key"

# Configuration
MODEL_OVERRIDE=""
SELECTED_MODEL=""

# Function to get custom models
get_custom_models() {
    local custom_models=()
    local model_dir="$SCRIPT_DIR/models"

    # Ensure model directory exists
    if [[ ! -d "$model_dir" ]]; then
        mkdir -p "$model_dir" 2>/dev/null || return 0
    fi

    # Find JSON files using simple for loop (most compatible)
    for json_file in $model_dir/*/config.json; do
        if [[ -f "$json_file" ]]; then
            local filename=$(basename "$json_file" .json)

            # Skip default model files
            case "$filename" in
                "glm"|"groq"|"minimax"|"openai"|"gemini"|"xai"|"ollama")
                    continue
                    ;;
            esac

            # Parse JSON for model info
            if command -v jq &> /dev/null; then
                local provider_name=$(jq -r '.provider_name // "Unknown"' "$json_file" 2>/dev/null)
                local description=$(jq -r '.description // "Custom Provider"' "$json_file" 2>/dev/null)
                # Ensure we got valid values
                [[ "$provider_name" == "null" || -z "$provider_name" ]] && provider_name="Unknown"
                [[ "$description" == "null" || -z "$description" ]] && description="Custom Provider"
                printf '%s:%s:%s\n' "$filename" "$provider_name" "$description"
            else
                # Fallback parsing without jq
                local provider_name=$(grep '"provider_name"' "$json_file" | sed 's/.*"provider_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/' 2>/dev/null)
                [[ -z "$provider_name" ]] && provider_name="$filename"
                local description=$(grep '"description"' "$json_file" | sed 's/.*"description"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/' 2>/dev/null)
                [[ -z "$description" ]] && description="Custom Provider"
                printf '%s:%s:%s\n' "$filename" "$provider_name" "$description"
            fi
        fi
    done
}

# Function to handle custom model
handle_custom_model() {
    local model_name="$1"
    local model_file="$SCRIPT_DIR/models/${model_name}/config.json"

    if [[ ! -f "$model_file" ]]; then
        echo -e "${RED}Error: Model configuration not found: $model_file${NC}"
        exit 1
    fi

    # Extract configuration
    if command -v jq &> /dev/null; then
        local api_base=$(jq -r '.api_base // ""' "$model_file" 2>/dev/null)
        local api_key=$(jq -r '.api_key // ""' "$model_file" 2>/dev/null)
        local model=$(jq -r '.model // ""' "$model_file" 2>/dev/null)
        local provider_name=$(jq -r '.provider_name // ""' "$model_file" 2>/dev/null)
    else
        echo -e "${RED}Error: jq is required for custom models. Install with: pkg install jq${NC}"
        exit 1
    fi

    # Get API key if not provided
    if [[ -z "$api_key" || "$api_key" == "your-api-key-here" ]]; then
        # Try to get from environment based on provider name
        case "${model_name,,}" in
            "qwen"|"qwen2")
                if [[ -n "$DASHSCOPE_API_KEY" ]]; then
                    api_key="$DASHSCOPE_API_KEY"
                    echo -e "${GREEN}✓ Using API key from DASHSCOPE_API_KEY${NC}"
                else
                    echo -e "${YELLOW}Enter Qwen API Key (https://bailian.console.aliyun.com/):${NC}"
                    read -s api_key
                fi
                ;;
            "deepseek")
                if [[ -n "$DEEPSEEK_API_KEY" ]]; then
                    api_key="$DEEPSEEK_API_KEY"
                    echo -e "${GREEN}✓ Using API key from DEEPSEEK_API_KEY${NC}"
                else
                    echo -e "${YELLOW}Enter Deepseek API Key:${NC}"
                    read -s api_key
                fi
                ;;
            "moonshot")
                if [[ -n "$MOONSHOT_API_KEY" ]]; then
                    api_key="$MOONSHOT_API_KEY"
                    echo -e "${GREEN}✓ Using API key from MOONSHOT_API_KEY${NC}"
                else
                    echo -e "${YELLOW}Enter Moonshot API Key:${NC}"
                    read -s api_key
                fi
                ;;
            "perplexity")
                if [[ -n "$PERPLEXITY_API_KEY" ]]; then
                    api_key="$PERPLEXITY_API_KEY"
                    echo -e "${GREEN}✓ Using API key from PERPLEXITY_API_KEY${NC}"
                else
                    echo -e "${YELLOW}Enter Perplexity API Key:${NC}"
                    read -s api_key
                fi
                ;;
            "cohere")
                if [[ -n "$COHERE_API_KEY" ]]; then
                    api_key="$COHERE_API_KEY"
                    echo -e "${GREEN}✓ Using API key from COHERE_API_KEY${NC}"
                else
                    echo -e "${YELLOW}Enter Cohere API Key:${NC}"
                    read -s api_key
                fi
                ;;
            "mistral")
                if [[ -n "$MISTRAL_API_KEY" ]]; then
                    api_key="$MISTRAL_API_KEY"
                    echo -e "${GREEN}✓ Using API key from MISTRAL_API_KEY${NC}"
                else
                    echo -e "${YELLOW}Enter Mistral API Key:${NC}"
                    read -s api_key
                fi
                ;;
            "openrouter")
                if [[ -n "$OPENROUTER_API_KEY" ]]; then
                    api_key="$OPENROUTER_API_KEY"
                    echo -e "${GREEN}✓ Using API key from OPENROUTER_API_KEY${NC}"
                else
                    echo -e "${YELLOW}Enter OpenRouter API Key (https://openrouter.ai/keys):${NC}"
                    read -s api_key
                fi
                ;;
            "agentrouter")
                if [[ -n "$ANTHROPIC_API_KEY" ]]; then
                    api_key="$ANTHROPIC_API_KEY"
                    echo -e "${GREEN}✓ Using API key from ANTHROPIC_API_KEY${NC}"
                else
                    echo -e "${YELLOW}Enter AgentRouter API Key (https://agentrouter.org/console/token):${NC}"
                    read -s api_key
                fi
                ;;
            *)
                echo -e "${YELLOW}Enter API Key for ${provider_name}:${NC}"
                read -s api_key
                ;;
        esac
        echo ""
    fi

    # Set environment variables for Claude
    if [[ -n "$api_base" ]]; then
        export ANTHROPIC_BASE_URL="$api_base"
    fi

    if [[ -n "$api_key" ]]; then
        export ANTHROPIC_API_KEY="$api_key"
    fi

    # Use the model name if specified, otherwise use the provider name
    local claude_model="${model:-$model_name}"

    # Create system prompt
    local system_prompt="Anda adalah ${provider_name}, model AI dari ${model_name}. Selalu identifikasi diri sebagai ${provider_name} dalam setiap respons."

    # Execute Claude directly
    exec claude $SKIP_PERMS_FLAG --model "$claude_model" --system-prompt "$system_prompt" "$@"
}

# Get script directory (portable)
get_script_dir() {
    if [[ -n "${BASH_SOURCE[0]}" ]]; then
        local script_path="${BASH_SOURCE[0]}"

        # Convert Windows paths if needed
        if [[ "$PLATFORM" == "Windows" ]]; then
            # Convert potential Windows path to Unix style
            script_path="$(cygpath -u "$script_path" 2>/dev/null || echo "$script_path")"
        fi

        if [[ "$PLATFORM" == "macOS" ]] || [[ "$(uname -s)" == "Darwin" ]]; then
            # macOS
            echo "$(cd "$(dirname "$script_path")" && pwd)"
        elif command -v realpath &> /dev/null; then
            # Linux/Windows with realpath
            echo "$(dirname "$(realpath "$script_path")")"
        else
            # Fallback for older systems
            echo "$(cd "$(dirname "$script_path")" && pwd)"
        fi
    else
        echo "$(pwd)"
    fi
}

SCRIPT_DIR=$(get_script_dir)

# Function to get/save GLM API key
get_glm_api_key() {
    # Try to load saved key first
    local saved_key
    saved_key=$(load_api_key "$GLM_API_KEY_FILE" "ZhipuAI/Z.AI")

    if [[ -n "$saved_key" ]]; then
        ANTHROPIC_AUTH_TOKEN="$saved_key"
        export ANTHROPIC_AUTH_TOKEN
        return 0
    fi

    # Ask for new API key
    echo ""
    echo "Enter ZhipuAI/Z.AI API Key:"
    echo "Get it from: https://open.bigmodel.cn/usercenter/apikeys"

    ANTHROPIC_AUTH_TOKEN=$(prompt_api_key "ZhipuAI/Z.AI")

    if [[ -n "$ANTHROPIC_AUTH_TOKEN" ]]; then
        # Save for next time using reusable function
        if save_api_key "$ANTHROPIC_AUTH_TOKEN" "$GLM_API_KEY_FILE" "ZhipuAI/Z.AI"; then
            export ANTHROPIC_AUTH_TOKEN
        else
            exit 1
        fi
    else
        echo -e "${RED}No API key provided${NC}" >&2
        exit 1
    fi
}

# Function to get/save MiniMax API key
get_minimax_api_key() {
    local api_key=""

    # Try to load saved key first
    api_key=$(load_api_key "$MINIMAX_API_KEY_FILE" "MiniMax")

    # Ask for new API key if not found
    if [[ -z "$api_key" ]]; then
        echo ""
        echo "Enter MiniMax API Key:"
        echo "Get it from: https://platform.minimax.io/"

        api_key=$(prompt_api_key "MiniMax")

        if [[ -n "$api_key" ]]; then
            # Save for next time using reusable function
            if ! save_api_key "$api_key" "$MINIMAX_API_KEY_FILE" "MiniMax"; then
                echo -e "${YELLOW}Warning: Continuing without saving API key${NC}" >&2
            fi
        else
            echo -e "${RED}Error: No API key provided${NC}" >&2
            exit 1
        fi
    fi

    # Export BOTH variables for compatibility
    # MiniMax endpoint uses Authorization header via ANTHROPIC_API_KEY
    export ANTHROPIC_API_KEY="$api_key"
    export ANTHROPIC_AUTH_TOKEN="$api_key"
}

check_dependencies() {
    echo -e "${BLUE}Checking dependencies...${NC}"

    # Check for python3
    if ! command -v python3 &> /dev/null; then
        echo -e "${RED}Error: python3 is not installed.${NC}"
        echo "Please install Python 3 first."
        exit 1
    fi

    # Check for claude CLI (OPTIONAL - won't exit if not found)
    if ! command -v claude &> /dev/null; then
        echo -e "${YELLOW}⚠️  'claude' command not found.${NC}"
        echo -e "${YELLOW}   For direct providers (GLM, MiniMax, OpenAI), you don't need it!${NC}"
        echo -e "${YELLOW}   For LiteLLM providers (Gemini, Groq, Ollama), install with:${NC}"
        echo -e "${YELLOW}   npm install -g @anthropic-ai/claude-code${NC}"
        echo ""
        read -p "Continue without claude CLI? (Y/n): " continue_without
        if [[ "$continue_without" =~ ^[Nn]$ ]]; then
            echo "Installing @anthropic-ai/claude-code..."
            npm install -g @anthropic-ai/claude-code || {
                echo -e "${YELLOW}Failed to install claude CLI. Continuing anyway...${NC}"
            }
        else
            echo -e "${GREEN}✓ Skipping claude CLI installation${NC}"
        fi
    else
        echo -e "${GREEN}✓ claude CLI found${NC}"
    fi

    # Check for npm (only needed for claude CLI installation)
    if command -v claude &> /dev/null; then
        if ! command -v npm &> /dev/null; then
            echo -e "${RED}Error: npm is not installed (needed for claude CLI).${NC}"
            echo "Please install npm first."
            exit 1
        fi
    fi
}

check_gemini_oauth() {
    # Check if we have ADC credentials
    local adc_path
    if [[ -n "$HOME" ]]; then
        adc_path="$HOME/.config/gcloud/application_default_credentials.json"
    else
        adc_path="$USERPROFILE/.config/gcloud/application_default_credentials.json"
    fi

    if [[ -f "$adc_path" ]]; then
        return 0
    fi

    # If not, check if gcloud is installed
    if command -v gcloud &> /dev/null; then
        echo -e "${BLUE}gcloud found. Attempting login...${NC}"
        gcloud auth application-default login
        return
    fi

    # Fallback to custom python script
    echo -e "${YELLOW}gcloud not found. Using lightweight Python Auth helper...${NC}"

    # Install dependency
    if ! python3 -m pip show google-auth-oauthlib &> /dev/null; then
        echo "Installing google-auth-oauthlib..."
        python3 -m pip install google-auth-oauthlib || true
    fi

    # Run helper script
    local auth_script="$SCRIPT_DIR/auth/gemini_auth.py"
    if [[ ! -f "$auth_script" ]]; then
        curl -fsSL https://raw.githubusercontent.com/zesbe/CliAllModel/main/gemini_auth.py -o "$SCRIPT_DIR/auth/gemini_auth.py" 2>/dev/null || true
        auth_script="$SCRIPT_DIR/auth/gemini_auth.py"
    fi

    if [[ -f "$auth_script" ]]; then
        python3 "$auth_script"
    fi

    if [[ ! -f "$adc_path" ]]; then
        echo -e "${RED}Authentication failed or cancelled.${NC}"
        exit 1
    fi
}

check_openai_oauth() {
    local cred_path
    if [[ -n "$HOME" ]]; then
        cred_path="$HOME/.config/openai/credentials.json"
    else
        cred_path="$USERPROFILE/.config/openai/credentials.json"
    fi

    if [[ ! -f "$cred_path" ]]; then
        echo -e "${YELLOW}No cached OpenAI OAuth token found. Launching helper...${NC}"

        # Install dependency
        python3 -m pip install requests > /dev/null 2>&1 || true

        local auth_script="$SCRIPT_DIR/auth/openai_auth.py"
        if [[ ! -f "$auth_script" ]]; then
            curl -fsSL https://raw.githubusercontent.com/zesbe/CliAllModel/main/openai_auth.py -o "$SCRIPT_DIR/auth/openai_auth.py" 2>/dev/null || true
            auth_script="$SCRIPT_DIR/auth/openai_auth.py"
        fi

        if [[ -f "$auth_script" ]]; then
            python3 "$auth_script"
        fi

        if [[ ! -f "$cred_path" ]]; then
            echo -e "${RED}OpenAI OAuth failed.${NC}"
            exit 1
        fi
    fi

    # Extract access token
    OPENAI_ACCESS_TOKEN=$(python3 -c "import json, os; print(json.load(open(os.path.expanduser('$cred_path')))['access_token'])" 2>/dev/null || echo "")
    export OPENAI_API_KEY="$OPENAI_ACCESS_TOKEN"
}
cleanup() {
    echo -e "\n${BLUE}Cleaning up processes...${NC}"
    
    # Clean up temp files
    if [[ -n "$SCRIPT_DIR" ]]; then
        rm -f "$SCRIPT_DIR"/.*_models.tmp 2>/dev/null || true
    fi
}

trap cleanup EXIT

# Interactive model selection
interactive_model_select() {
    local provider=$1
    local model_file="$SCRIPT_DIR/models/${provider}/config.json"

    if [[ ! -f "$model_file" ]]; then
        echo -e "${RED}Config file not found: $model_file${NC}"
        return 1
    fi

    # Display models using Python (flush output to stderr)
    python3 << EOF >&2
import json
import sys

with open('$model_file', 'r') as f:
    data = json.load(f)

print('')
print('=== Select Model ===')
for i, model in enumerate(data['models'], 1):
    name = model['name']
    desc = model['description']
    print(f'{i}) {name} - {desc}')
print('')
print('Available Models:')
for i, model in enumerate(data['models'], 1):
    name = model['name']
    desc = model['description']
    print(f'  {i}. {name} - {desc}')
print('')
sys.stderr.flush()
EOF

    # Save model list to temp file and get count
    model_count=$(python3 << EOF
import json
with open('$model_file', 'r') as f:
    data = json.load(f)
models = [m['id'] for m in data['models']]
with open('$SCRIPT_DIR/.${provider}_models.tmp', 'w') as f:
    for m in models:
        f.write(m + '\n')
print(len(models))
EOF
)

    # Wait for user input
    echo -n "Select model [1-$model_count]: "
    read choice

    # Validate choice
    if [[ -z "$choice" ]]; then
        echo -e "${RED}Error: No selection made${NC}" >&2
        return 1
    elif ! [[ "$choice" =~ ^[0-9]+$ ]]; then
        echo -e "${RED}Error: Please enter a valid number${NC}" >&2
        return 1
    elif [[ "$choice" -lt 1 ]] || [[ "$choice" -gt "$model_count" ]]; then
        echo -e "${RED}Error: Please enter a number between 1 and $model_count${NC}" >&2
        return 1
    fi

    # Read model ID from temp file
    if [[ -f "$SCRIPT_DIR/.${provider}_models.tmp" ]]; then
        local model_ids
        model_ids=($(cat "$SCRIPT_DIR/.${provider}_models.tmp"))
        local idx=$((choice - 1))

        if [[ $idx -ge 0 ]] && [[ $idx -lt ${#model_ids[@]} ]]; then
            local selected="${model_ids[$idx]}"
            echo -e "${GREEN}✓ Selected: $selected${NC}"
            echo "$selected"
            rm -f "$SCRIPT_DIR/.${provider}_models.tmp"
            return 0
        else
            echo -e "${RED}Invalid choice: $choice${NC}"
            echo "Please select 1-${#model_ids[@]}"
        fi
    else
        echo -e "${RED}Model list not found${NC}"
    fi

    return 1
}

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -m|--model)
            MODEL_OVERRIDE="$2"
            shift 2
            ;;
        *)
            if [[ -z "$choice" ]]; then
                choice="$1"
            fi
            shift
            ;;
    esac
done

# Handle direct argument for custom models (22+ since we added Letta at 17)
if [[ -n "$1" ]] && [[ "$1" =~ ^[0-9]+$ ]] && [[ "$1" -ge 22 ]]; then
    choice="$1"
    export CHOICE="$choice"

    # Check if it's model manager - get actual number
    if [[ -f "$SCRIPT_DIR/scripts/add-model-manual.sh" ]]; then
        # Count custom models
        custom_count=0
        while IFS= read -r model_info; do
            if [[ -n "$model_info" ]]; then
                ((custom_count++))
            fi
        done < <(get_custom_models)

        model_manager_num=$((22 + custom_count))
        if [[ $choice -eq $model_manager_num ]]; then
            exec "$SCRIPT_DIR/scripts/add-model-manual.sh"
        fi
    fi

    # Handle custom model selection
    custom_index=$((choice - 22))
    count=0
    while IFS= read -r model_info; do
        if [[ -n "$model_info" ]]; then
            if [[ $count -eq $custom_index ]]; then
                IFS=':' read -r filename provider_name description <<< "$model_info"
                echo -e "${BLUE}Using ${provider_name}...${NC}"
                handle_custom_model "$filename" "${@:2}"
                exit 0
            fi
            ((count++))
        fi
    done < <(get_custom_models)
    echo -e "${RED}Invalid custom model selection${NC}"
    exit 1
fi

# Handle direct CHOICE (for environment variable or argument)
if [[ -n "$CHOICE" ]]; then
echo "DEBUG: choice=$choice"
    choice="$CHOICE"
fi

# Check dependencies
check_dependencies() {
    # Check for required commands
    local missing_deps=()

    if ! command -v jq &> /dev/null; then
        echo -e "${YELLOW}Warning: jq not found. JSON parsing will be limited.${NC}"
        echo -e "${YELLOW}Install jq: pkg install jq (Termux) or apt-get install jq${NC}"
        echo ""
    fi

    if [[ "$PLATFORM" == "Windows" ]] && ! command -v nano &> /dev/null && ! command -v vim &> /dev/null; then
        echo -e "${YELLOW}Warning: No text editor found. Install nano or vim.${NC}"
        echo ""
    fi
}

save_chat_context() {
    local context_file="/tmp/claude_chat_context.txt"
    if [[ -t 0 ]]; then
        echo "# Chat context saved at $(date)" > "$context_file"
        echo "# Current conversation:" >> "$context_file"
        echo "Use this context to continue the conversation with a new provider." >> "$context_file"
        echo "" >> "$context_file"
    fi
}

continue_chat_with_new_provider() {
    echo -e "\n${YELLOW}=== Switch Provider (Continue Chat) ===${NC}"
    echo "Your current chat context will be preserved."
    echo ""

    # Show available providers for switching
    echo "Available providers:"
    echo "1) MiniMax"
    echo "2) Google Gemini (API Key)"
    echo "3) Google Gemini (OAuth)"
    echo "4) OpenAI"
    echo "5) OpenAI (OAuth)"
    echo "6) xAI / Grok"
    echo "7) ZhipuAI / GLM"
    echo "8) Groq"
    echo "9) Perplexity"
    echo "10) Cohere"
    echo "11) DeepSeek"
    echo "12) Mistral"
    echo "13) Moonshot"
    echo "14) Qwen"
    echo "15) OpenRouter"
    echo "16) Ollama (Local)"
    echo "0) Cancel"
    echo ""

    read -p "Choose new provider [0-16]: " switch_choice

    case $switch_choice in
        0) echo "Cancelled provider switch."; return 0 ;;
        1) setup_minimax ;;
        2) setup_gemini_api ;;
        3) setup_gemini_oauth ;;
        4) setup_openai ;;
        5) setup_openai_oauth ;;
        6) setup_xai ;;
        7) setup_glm ;;
        8) setup_groq ;;
        9) setup_perplexity ;;
        10) setup_cohere ;;
        11) setup_deepseek ;;
        12) setup_mistral ;;
        13) setup_moonshot ;;
        14) setup_qwen ;;
        15) setup_openrouter ;;
        16) setup_ollama ;;
        *) echo "Invalid choice."; return 1 ;;
    esac

    # Save context before switching
    save_chat_context

    echo -e "${GREEN}✓ Provider switched successfully!${NC}"
    echo -e "${BLUE}Note: Chat context has been saved. You can reference previous messages in your next prompt.${NC}"
}

# Provider setup functions
setup_minimax() {
    API_KEY=$(load_api_key "minimax" "MiniMax")
    if [[ $? -eq 0 ]]; then
        check_dependencies
        echo -e "${BLUE}Starting MiniMax session...${NC}"
        export MINIMAX_API_KEY="$API_KEY"
        exec claude $SKIP_PERMS_FLAG "$@"
    fi
}

setup_gemini_api() {
    API_KEY=$(load_api_key "gemini" "Google Gemini")
    if [[ $? -eq 0 ]]; then
        check_dependencies
        echo -e "${BLUE}Configuring for Google Gemini (API Key)...${NC}"
        echo -e "${YELLOW}Get API Key: https://aistudio.google.com/app/apikey${NC}"
        export GEMINI_API_KEY="$API_KEY"
        exec claude $SKIP_PERMS_FLAG "$@"
    fi
}

setup_gemini_oauth() {
    if [[ ! -f "$HOME/.google-credentials.json" ]]; then
        echo -e "${YELLOW}⚠️ Google OAuth credentials not found. Running setup...${NC}"
        python3 "$SCRIPT_DIR/setup_google_internal_auth.py" || setup_google_oauth_manual
    fi

    if [[ -f "$HOME/.google-credentials.json" ]]; then
        check_dependencies
        echo -e "${BLUE}Using Google Internal Authentication (AntiGravity)${NC}"
        export CLOUD_ML helicopterauto
        GOOGLE_AUTH_TOKEN=$(python3 "$SCRIPT_DIR/get_google_access_token.py")
        exec claude $SKIP_PERMS_FLAG "$@"
    fi
}

setup_openai() {
    API_KEY=$(load_api_key "openai" "OpenAI")
    if [[ $? -eq 0 ]]; then
        check_dependencies
        echo -e "${BLUE}Configuring for OpenAI...${NC}"
        export OPENAI_API_KEY="$API_KEY"
        exec claude $SKIP_PERMS_FLAG "$@"
    fi
}

setup_openai_oauth() {
    echo -e "${BLUE}OpenAI OAuth flow...${NC}"
    exec "$SCRIPT_DIR/handle_oauth_callback.sh"
}

setup_xai() {
    API_KEY=$(load_api_key "xai" "xAI")
    if [[ $? -eq 0 ]]; then
        check_dependencies
        echo -e "${BLUE}Configuring for xAI / Grok...${NC}"
        echo -e "${YELLOW}Get Key: https://console.x.ai/${NC}"
        export XAI_API_KEY="$API_KEY"
        exec claude $SKIP_PERMS_FLAG "$@"
    fi
}

setup_glm() {
    # Auto-use Z_AI_API_KEY from .env if available
    if [[ -n "$Z_AI_API_KEY" ]]; then
        API_KEY="$Z_AI_API_KEY"
    else
        API_KEY=$(load_api_key "glm" "GLM")
        [[ $? -ne 0 ]] && return 1
    fi
    check_dependencies
    MODEL=$(select_glm_model)
    echo -e "${BLUE}Configuring for ZhipuAI / GLM...${NC}"
    export ANTHROPIC_BASE_URL="https://api.z.ai/api/anthropic"
    export ANTHROPIC_API_KEY="$API_KEY"
    export CLAUDE_MODEL="$MODEL"
    exec claude $SKIP_PERMS_FLAG --model "$MODEL" "$@"
}

setup_groq() {
    API_KEY=$(load_api_key "groq" "Groq")
    if [[ $? -eq 0 ]]; then
        check_dependencies
        echo -e "${BLUE}Configuring for Groq...${NC}"
        export GROQ_API_KEY="$API_KEY"
        exec claude $SKIP_PERMS_FLAG "$@"
    fi
}

setup_perplexity() {
    API_KEY=$(load_api_key "perplexity" "Perplexity")
    if [[ $? -eq 0 ]]; then
        check_dependencies
        echo -e "${BLUE}Configuring for Perplexity...${NC}"
        echo -e "${YELLOW}Get Key: https://console.perplexity.ai/${NC}"
        export PERPLEXITY_API_KEY="$API_KEY"
        exec claude $SKIP_PERMS_FLAG "$@"
    fi
}

setup_cohere() {
    API_KEY=$(load_api_key "cohere" "Cohere")
    if [[ $? -eq 0 ]]; then
        check_dependencies
        echo -e "${BLUE}Configuring for Cohere...${NC}"
        export COHERE_API_KEY="$API_KEY"
        exec claude $SKIP_PERMS_FLAG "$@"
    fi
}

setup_deepseek() {
    API_KEY=$(load_api_key "deepseek" "DeepSeek")
    if [[ $? -eq 0 ]]; then
        check_dependencies
        echo -e "${BLUE}Configuring for DeepSeek (Anthropic API)...${NC}"
        export ANTHROPIC_AUTH_TOKEN="$API_KEY"
        export ANTHROPIC_BASE_URL="https://api.deepseek.com/anthropic"
        export ANTHROPIC_API_KEY="$API_KEY"

        # Quick model selection
        echo ""
        echo -e "${YELLOW}Select DeepSeek model:${NC}"
        echo "  1) deepseek-chat      (Fast - Default)"
        echo "  2) deepseek-reasoner  (Deep Analysis)"
        read -p "Choice [1-2, default: 1]: " ds_choice
        case $ds_choice in
            2) MODEL_NAME="deepseek-reasoner" ;;
            *) MODEL_NAME="deepseek-chat" ;;
        esac
        echo -e "${GREEN}✓ Using: $MODEL_NAME${NC}"
        export CLAUDE_MODEL="$MODEL_NAME"
        exec claude $SKIP_PERMS_FLAG --model "$MODEL_NAME" --system-prompt "You are DeepSeek, an AI assistant by DeepSeek." "$@"
    fi
}

setup_mistral() {
    API_KEY=$(load_api_key "mistral" "Mistral")
    if [[ $? -eq 0 ]]; then
        check_dependencies
        echo -e "${BLUE}Configuring for Mistral...${NC}"
        export MISTRAL_API_KEY="$API_KEY"
        exec claude $SKIP_PERMS_FLAG "$@"
    fi
}

setup_moonshot() {
    API_KEY=$(load_api_key "moonshot" "Moonshot")
    if [[ $? -eq 0 ]]; then
        check_dependencies
        echo -e "${BLUE}Configuring for Moonshot...${NC}"
        export MOONSHOT_API_KEY="$API_KEY"
        exec claude $SKIP_PERMS_FLAG "$@"
    fi
}

setup_qwen() {
    API_KEY=$(load_api_key "qwen" "Qwen")
    if [[ $? -eq 0 ]]; then
        check_dependencies
        echo -e "${BLUE}Configuring for Qwen...${NC}"
        export QWEN_API_KEY="$API_KEY"
        exec claude $SKIP_PERMS_FLAG "$@"
    fi
}

setup_openrouter() {
    API_KEY=$(load_api_key "openrouter" "OpenRouter")
    if [[ $? -eq 0 ]]; then
        check_dependencies
        echo -e "${BLUE}Configuring for OpenRouter...${NC}"
        export OPENROUTER_API_KEY="$API_KEY"
        exec claude $SKIP_PERMS_FLAG "$@"
    fi
}

setup_ollama() {
    check_dependencies
    echo -e "${BLUE}Configuring for Ollama (Local)...${NC}"
    echo -e "${YELLOW}Note: Make sure Ollama is running locally${NC}"
    export ANTHROPIC_BASE_URL="http://localhost:11434/v1"
    export ANTHROPIC_API_KEY="ollama"
    exec claude --no-chrome "$@"
}

# Main Menu
if [[ -z "$choice" ]]; then
    clear
    echo -e "${GREEN}=====================================${NC}"
    echo -e "${GREEN}    Claude Code Multi-Model Launcher ${NC}"
    echo -e "${GREEN}══════════════════════════════════════════════════════════════════${NC}"
    echo -e "${BLUE}                    🤖 AI MODELS & PROVIDERS${NC}"
    echo -e "${GREEN}══════════════════════════════════════════════════════════════════${NC}"
    echo ""
    echo -e "${YELLOW}📱 MAIN MODELS:${NC}"
    echo "  1) MiniMax (Direct Anthropic API)     🚀 Fast & Reliable"
    echo "  2) Google Gemini (API Key - AI Studio)  🧠 Google AI"
    echo "  3) Universal OAuth (Auto-Setup)      🔥 37+ Models (GPT-5, Claude, Gemini)"
    echo "  4) OpenAI (API Key)                     🤖 GPT Models"
    echo "  5) OpenAI (OAuth - Experimental)          🔄 Auto-auth"
    echo ""
    echo -e "${YELLOW}🌟 POPULAR PROVIDERS:${NC}"
    echo "  6) xAI / Grok (API Key)                 🚀 Real-time"
    echo "  7) ZhipuAI / GLM (API Key)              🇨🇳 Chinese AI"
    echo "  8) Groq (API Key)                      ⚡ Ultra-fast"
    echo "  9) Perplexity (Web Search)             🔍 Live Data"
    echo " 10) Cohere (API Key)                     📝 Business AI"
    echo " 11) DeepSeek (API Key)                   🧠 V3.2 (Chat + Reasoner)"
    echo ""
    echo -e "${YELLOW}🏠 LOCAL & SPECIALIZED:${NC}"
    echo " 12) Ollama (Local Models)                💻 Self-hosted"
    echo " 13) Mistral (API Key)                    🇫🇷 European AI (15 Models)"
    echo " 14) Moonshot (API Key)                   🌙 Kawaii AI"
    echo " 15) Qwen (API Key)                       🇨🇳 Alibaba"
    echo " 16) OpenRouter (Multi-provider)           🔀 All-in-one"
    echo " 17) Letta Memory Agent                  🧠 Multi-Backend (Claude/Gemini/OpenAI)"
    echo ""
    echo -e "${YELLOW}🔧 TOOLS & UTILITIES:${NC}"
    echo " 18) 🔑 API Key Manager                   🔐 View/Edit/Delete Keys"
    echo " 19) 🤖 Claude Master Tool                 🎛️ Advanced UI"
    echo " 20) ➕ Add/Edit/Delete Models               ⚙️ Custom Models"
    echo ""

    echo -e "${GREEN}══════════════════════════════════════════════════════════════════${NC}"
    read -p "Enter choice [1-20]: " choice
fi

# Function to save and load API keys persistently
save_api_key() {
    local key="$1"
    local key_file="$2"
    local provider_name="$3"

    # Validate key is not empty
    if [[ -z "$key" || "$key" =~ ^[[:space:]]*$ ]]; then
        echo -e "${RED}✗ API key cannot be empty${NC}"
        return 1
    fi

    echo "$key" > "$key_file"
    chmod 600 "$key_file"
    echo -e "${GREEN}✓ $provider_name API key saved to $key_file${NC}"
}

# Check and install CCS if needed
check_and_install_ccs() {
    local provider_name="$1"
    
    # Check if CCS is installed
    if command -v ccs &> /dev/null; then
        echo -e "${GREEN}✓ CCS sudah terinstall${NC}"
        return 0
    fi
    
    echo -e "${YELLOW}⚠️  CCS (Claude Code Switch) belum terinstall${NC}"
    echo ""
    echo -e "${CYAN}CCS diperlukan untuk Universal OAuth (GPT-5, Claude Opus 4.5, Gemini 3)${NC}"
    echo ""
    echo "Install CCS akan:"
    echo "  • Download @kaitranntt/ccs via npm"
    echo "  • Ukuran: ~10MB"
    echo "  • Waktu: ~30 detik"
    echo ""
    read -p "Install CCS sekarang? [Y/n]: " install_ccs
    
    if [[ "$install_ccs" =~ ^[Nn] ]]; then
        echo -e "${RED}✗ CCS tidak diinstall. Kembali ke menu...${NC}"
        sleep 1
        exec "$0"
    fi
    
    echo ""
    echo -e "${BLUE}📦 Installing CCS...${NC}"
    
    # Install CCS via npm
    if npm install -g @kaitranntt/ccs; then
        echo ""
        echo -e "${GREEN}✓ CCS berhasil diinstall!${NC}"
        echo ""
        
        # Verify installation
        if command -v ccs &> /dev/null; then
            echo -e "${GREEN}✓ CCS version: $(ccs --version 2>&1 | head -1)${NC}"
            echo ""
            echo -e "${CYAN}Selanjutnya Anda perlu authenticate untuk $provider_name:${NC}"
            echo -e "${YELLOW}Command: ccs ${provider_name,,} --auth${NC}"
            echo ""
            read -p "Authenticate sekarang? [Y/n]: " do_auth
            
            if [[ ! "$do_auth" =~ ^[Nn] ]]; then
                echo ""
                echo -e "${BLUE}🔐 Membuka browser untuk authentication...${NC}"
                ccs "${provider_name,,}" --auth
                echo ""
                echo -e "${GREEN}✓ Authentication selesai!${NC}"
                echo ""
                read -p "Press Enter untuk melanjutkan..."
            else
                echo ""
                echo -e "${YELLOW}⚠️  Jangan lupa authenticate nanti dengan: ccs ${provider_name,,} --auth${NC}"
                echo ""
                read -p "Press Enter untuk kembali ke menu..."
                exec "$0"
            fi
        else
            echo -e "${RED}✗ CCS install failed. Coba lagi dengan: npm install -g @kaitranntt/ccs${NC}"
            read -p "Press Enter untuk kembali..."
            exec "$0"
        fi
    else
        echo ""
        echo -e "${RED}✗ CCS install gagal!${NC}"
        echo ""
        echo "Troubleshooting:"
        echo "  1. Check internet connection"
        echo "  2. Try: npm cache clean --force"
        echo "  3. Manual install: npm install -g @kaitranntt/ccs"
        echo ""
        read -p "Press Enter untuk kembali..."
        exec "$0"
    fi
}

load_api_key_to_var() {
    local key_file="$1"
    local var_name="$2"

    if [[ -f "$key_file" ]]; then
        local key=$(cat "$key_file" 2>/dev/null | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        if [[ -n "$key" ]]; then
            # Use eval to ensure variable is set in current scope
            eval "$var_name='$key'"
            export "$var_name"
            return 0
        fi
    fi
    return 1
}

get_api_key_with_save() {
    local var_name="$1"
    local key_file="$2"
    local provider_name="$3"
    local key_url="$4"

    # Try to load from environment first
    if [[ -z "${!var_name}" ]]; then
        # Try to load from file
        load_api_key_to_var "$key_file" "$var_name"
    fi

    # Still empty? Ask user
    while [[ -z "${!var_name}" ]]; do
        echo "Get Key: $key_url"
        read -p "Enter $provider_name API Key: " key_input

        # Validate input
        if [[ -z "$key_input" || "$key_input" =~ ^[[:space:]]*$ ]]; then
            echo -e "${RED}✗ API key cannot be empty. Please try again.${NC}"
            continue
        fi

        export "$var_name=$key_input"
        save_api_key "$key_input" "$key_file" "$provider_name"
        break
    done

    # Save current key if not already saved
    if [[ -n "${!var_name}" && ! -f "$key_file" ]]; then
        save_api_key "${!var_name}" "$key_file" "$provider_name"
    fi
}

# API Key Manager - Built-in function to manage all API keys
api_key_manager() {
    while true; do
        clear
        echo -e "${GREEN}═════════════════════════════════════════════${NC}"
        echo -e "${GREEN}           🔑 API KEY MANAGER                ${NC}"
        echo -e "${GREEN}═════════════════════════════════════════════${NC}"
        echo ""

        # All providers
        local all_providers=(
            "minimax:MiniMax:$HOME/.minimax_api_key"
            "gemini:Google Gemini:$HOME/.gemini_api_key"
            "openai:OpenAI:$HOME/.openai_api_key"
            "xai:xAI (Grok):$HOME/.xai_api_key"
            "glm:ZhipuAI (GLM):$HOME/.glm_api_key"
            "groq:Groq:$HOME/.groq_api_key"
            "perplexity:Perplexity:$HOME/.perplexity_api_key"
            "cohere:Cohere:$HOME/.cohere_api_key"
            "deepseek:DeepSeek:$HOME/.deepseek_api_key"
            "ollama:Ollama:$HOME/.ollama_api_key"
            "mistral:Mistral:$HOME/.mistral_api_key"
            "moonshot:Moonshot:$HOME/.moonshot_api_key"
            "qwen:Qwen (Alibaba):$HOME/.qwen_api_key"
            "openrouter:OpenRouter:$HOME/.openrouter_api_key"
            "letta:Letta AI:$HOME/.letta_api_key"
        )

        # Build array of saved keys only
        local saved_keys=()
        for key_info in "${all_providers[@]}"; do
            IFS=':' read -r id name file <<< "$key_info"
            if [[ -f "$file" ]]; then
                local key_value=$(cat "$file" 2>/dev/null | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
                if [[ -n "$key_value" ]]; then
                    saved_keys+=("$id:$name:$file:$key_value")
                fi
            fi
        done

        echo -e "${YELLOW}📋 Saved API Keys:${NC}"
        echo ""
        if [[ ${#saved_keys[@]} -eq 0 ]]; then
            echo -e "${RED}  No API keys saved yet${NC}"
        else
            for i in "${!saved_keys[@]}"; do
                IFS=':' read -r id name file key_value <<< "${saved_keys[$i]}"
                local key_len=${#key_value}
                if [[ $key_len -gt 12 ]]; then
                    local masked="${key_value:0:8}...${key_value: -4}"
                else
                    local masked="${key_value:0:4}..."
                fi
                printf "  %-3s %-20s %s\n" "$((i+1)))" "$name" "$masked"
            done
        fi

        echo ""
        echo -e "${YELLOW}🔧 Actions:${NC}"
        echo "  ${BLUE}Just enter NUMBER to edit that key!${NC}"
        echo "  v) View full API key"
        echo "  d) Delete API key"
        echo "  a) Add new API key"
        echo "  c) Clear all API keys"
        echo "  b) Back to main menu"
        echo ""
        echo -e "${GREEN}═════════════════════════════════════════════${NC}"

        read -p "Choose [number/action]: " action

        # Check if input is a number for quick edit
        if [[ "$action" =~ ^[0-9]+$ ]]; then
            local idx=$((action - 1))
            if [[ $idx -ge 0 && $idx -lt ${#saved_keys[@]} ]]; then
                IFS=':' read -r id name file old_key <<< "${saved_keys[$idx]}"
                echo ""
                echo -e "${YELLOW}Editing: $name${NC}"
                echo -e "${YELLOW}Current: ${old_key:0:8}...${old_key: -4}${NC}"
                read -p "Enter new API key: " new_key
                if [[ -n "$new_key" ]]; then
                    save_api_key "$new_key" "$file" "$name"
                    echo -e "${GREEN}✓ API key updated${NC}"
                else
                    echo -e "${RED}✗ Empty - not saved${NC}"
                fi
                echo ""
                read -p "Press Enter to continue..."
            else
                echo -e "${RED}Invalid number${NC}"
                sleep 1
            fi
            continue
        fi

        case "$action" in
            v|V)
                if [[ ${#saved_keys[@]} -eq 0 ]]; then
                    echo -e "${RED}No API keys saved${NC}"
                    sleep 1
                    continue
                fi
                read -p "Enter number [1-${#saved_keys[@]}]: " num
                if [[ "$num" =~ ^[0-9]+$ ]]; then
                    local idx=$((num - 1))
                    if [[ $idx -ge 0 && $idx -lt ${#saved_keys[@]} ]]; then
                        IFS=':' read -r id name file key_value <<< "${saved_keys[$idx]}"
                        echo ""
                        echo -e "${GREEN}API Key for $name:${NC}"
                        echo "$key_value"
                    else
                        echo -e "${RED}Invalid number${NC}"
                    fi
                else
                    echo -e "${RED}Invalid input${NC}"
                fi
                echo ""
                read -p "Press Enter to continue..."
                ;;

            d|D)
                if [[ ${#saved_keys[@]} -eq 0 ]]; then
                    echo -e "${RED}No API keys to delete${NC}"
                    sleep 1
                    continue
                fi
                read -p "Enter number [1-${#saved_keys[@]}]: " num
                if [[ "$num" =~ ^[0-9]+$ ]]; then
                    local idx=$((num - 1))
                    if [[ $idx -ge 0 && $idx -lt ${#saved_keys[@]} ]]; then
                        IFS=':' read -r id name file key_value <<< "${saved_keys[$idx]}"
                        read -p "Delete $name key? (y/n): " confirm
                        if [[ "$confirm" == "y" || "$confirm" == "Y" ]]; then
                            rm -f "$file"
                            echo -e "${GREEN}✓ Deleted${NC}"
                        else
                            echo "Cancelled"
                        fi
                    else
                        echo -e "${RED}Invalid number${NC}"
                    fi
                else
                    echo -e "${RED}Invalid input${NC}"
                fi
                echo ""
                read -p "Press Enter to continue..."
                ;;

            a|A)
                echo ""
                echo -e "${YELLOW}Available providers:${NC}"
                for i in "${!all_providers[@]}"; do
                    IFS=':' read -r id name file <<< "${all_providers[$i]}"
                    printf "  %-3s %-15s (%s)\n" "$((i+1)))" "$id" "$name"
                done
                echo ""
                read -p "Enter number [1-${#all_providers[@]}]: " num
                if [[ "$num" =~ ^[0-9]+$ ]]; then
                    local idx=$((num - 1))
                    if [[ $idx -ge 0 && $idx -lt ${#all_providers[@]} ]]; then
                        IFS=':' read -r id name file <<< "${all_providers[$idx]}"
                        read -p "Enter API key for $name: " new_key
                        if [[ -n "$new_key" ]]; then
                            save_api_key "$new_key" "$file" "$name"
                        else
                            echo -e "${RED}✗ Empty - not saved${NC}"
                        fi
                    else
                        echo -e "${RED}Invalid number${NC}"
                    fi
                else
                    echo -e "${RED}Invalid input${NC}"
                fi
                echo ""
                read -p "Press Enter to continue..."
                ;;

            c|C)
                read -p "Delete ALL API keys? Type 'yes' to confirm: " confirm
                if [[ "$confirm" == "yes" ]]; then
                    for key_info in "${all_providers[@]}"; do
                        IFS=':' read -r id name file <<< "$key_info"
                        rm -f "$file"
                    done
                    echo -e "${GREEN}✓ All keys cleared${NC}"
                else
                    echo "Cancelled"
                fi
                echo ""
                read -p "Press Enter to continue..."
                ;;

            b|B)
                return 0
                ;;

            *)
                echo -e "${RED}Invalid action${NC}"
                sleep 1
                ;;
        esac
    done
}

# Function to save chat context when switching providers
save_chat_context() {
    local context_file="$HOME/.claude-chat-context.json"
    local provider="$1"
    local model="$2"
    local message="$3"

    # Create context if not exists
    if [[ ! -f "$context_file" ]]; then
        echo "[] " > "$context_file"
    fi

    # Save using jq if available, otherwise simple append
    if command -v jq &> /dev/null; then
        local temp_file=$(mktemp)
        jq --argjson "$provider" --argjson "$model" --argjson "$message" '. + [$provider, $model, $message]' "$context_file" > "$temp_file" && mv "$temp_file" "$context_file"
    else
        echo "Provider: $provider, Model: $model, Message: $message" >> "$HOME/.claude-chat-history.log"
    fi
}

# Function to continue chat with new provider
continue_chat_with_new_provider() {
    local new_provider="$1"
    local new_model="$2"

    echo -e "\n${BLUE}🔄 Switching to new provider: ${NC}"
    echo -e "${YELLOW}Note: Previous conversation context will be maintained${NC}"
    echo -e "${YELLOW}Use 'clear' command in chat to start fresh if needed${NC}\n"

    # Set up new provider
    case $new_provider in
        1) setup_minimax;;
        2) setup_gemini;;
        4) setup_openai;;
        6) setup_xai;;
        7) setup_glm;;
        8) setup_groq;;
        9) setup_perplexity;;
        10) setup_cohere;;
        11) setup_deepseek;;
        13) setup_mistral;;
        14) setup_moonshot;;
        15) setup_qwen;;
        16) setup_openrouter;;
        *) echo -e "${RED}Invalid provider choice${NC}"; return 1;;
    esac

    # Start chat with context preserved
    exec claude $SKIP_PERMS_FLAG --model "$new_model" "$@"
}

# Model name will be set dynamically based on provider selection
echo "DEBUG: Starting case statement, choice=$choice"

case $choice in
    1)
        # MiniMax Direct
        echo -e "${BLUE}Configuring for MiniMax...${NC}"

        # Get API key with persistent storage
        get_api_key_with_save "MINIMAX_API_KEY" "$HOME/.minimax_api_key" "MiniMax" "https://platform.minimax.io/"

        export ANTHROPIC_BASE_URL="https://api.minimax.io/anthropic"
        export ANTHROPIC_API_KEY="$MINIMAX_API_KEY"
        echo -e "${GREEN}✓ MiniMax API configured${NC}"

        # Model selection menu
        echo ""
        echo -e "${YELLOW}Available MiniMax models:${NC}"
        echo "  🚀 minimax-m2.1              (NEW! Latest coding model - 10B params)     [m2]"
        echo "  💬 claude-3-5-sonnet-20241022 (Claude-compatible API endpoint)           [sonnet]"
        echo "  ⚡ abab6.5                     (General purpose model)                    [6.5]"
        echo "  🧠 abab6.5s                    (Fast variant)                             [6.5s]"
        echo "  📝 abab5.5                     (Lighter model)                            [5.5]"
        echo ""
        echo -e "${GREEN}Shortcuts:${NC}"
        echo "  'm2' or 'm2.1'  → minimax-m2.1 (Recommended for coding & agentic workflows)"
        echo "  'sonnet'        → claude-3-5-sonnet-20241022"
        echo "  '6.5'           → abab6.5"
        echo ""
        echo -e "${BLUE}💡 MiniMax M2.1 Features:${NC}"
        echo "  • Optimized for multi-language programming (Rust, Java, Go, C++, TypeScript, etc.)"
        echo "  • 10B activated parameters, exceptional latency & cost efficiency"
        echo "  • 49.4% on Multi-SWE-Bench, 72.5% on SWE-Bench Multilingual"
        echo "  • Perfect for coding assistants, agents, and real-world tasks"
        echo ""

        # Use MiniMax M2.1 as default
        MODEL_NAME="minimax-m2.1"
        echo -e "${GREEN}✓ Default model: minimax-m2.1${NC}"
        read -p "Enter Model Name [default: minimax-m2.1]: " input_model
        [[ -n "$input_model" ]] && MODEL_NAME=$input_model

        # Map shortcuts to full model names
        case "$MODEL_NAME" in
            "m2"|"m2.1"|"M2"|"M2.1")
                FINAL_MODEL="minimax-m2.1"
                echo -e "${GREEN}✓ Selected: minimax-m2.1 (Latest coding model)${NC}"
                ;;
            "sonnet"|"claude")
                FINAL_MODEL="claude-3-5-sonnet-20241022"
                echo -e "${GREEN}✓ Selected: claude-3-5-sonnet-20241022${NC}"
                ;;
            "6.5"|"abab6.5")
                FINAL_MODEL="abab6.5"
                echo -e "${GREEN}✓ Selected: abab6.5${NC}"
                ;;
            "6.5s"|"abab6.5s")
                FINAL_MODEL="abab6.5s"
                echo -e "${GREEN}✓ Selected: abab6.5s (Fast)${NC}"
                ;;
            "5.5"|"abab5.5")
                FINAL_MODEL="abab5.5"
                echo -e "${GREEN}✓ Selected: abab5.5 (Lighter)${NC}"
                ;;
            *)
                FINAL_MODEL="$MODEL_NAME"
                echo -e "${GREEN}✓ Using custom model: $MODEL_NAME${NC}"
                ;;
        esac

        echo -e "${BLUE}🚀 Starting MiniMax chat with $FINAL_MODEL...${NC}"
        exec claude $SKIP_PERMS_FLAG --model "$FINAL_MODEL" --system-prompt "Anda adalah MiniMax AI. Model aktif: $FINAL_MODEL. Selalu identifikasi diri sebagai MiniMax dalam setiap respons." "$@"
        ;;
    2)
        # Gemini API Key - Direct Integration
        echo -e "${BLUE}Configuring for Gemini (AI Studio)...${NC}"

        # Get API key with persistent storage
        if [[ -z "$GEMINI_API_KEY" ]]; then
            # Try to load from file
            load_api_key_to_var "$HOME/.gemini_api_key" "GEMINI_API_KEY"
        fi

        if [[ -z "$GEMINI_API_KEY" ]]; then
            echo "Get Key: https://aistudio.google.com/app/apikey"
            read -s -p "Enter Gemini API Key: " GEMINI_API_KEY
            echo ""
            save_api_key "$GEMINI_API_KEY" "$HOME/.gemini_api_key" "Gemini"
        else
            # Save current key if not already saved
            if [[ ! -f "$HOME/.gemini_api_key" ]]; then
                save_api_key "$GEMINI_API_KEY" "$HOME/.gemini_api_key" "Gemini"
            fi
        fi
        export GEMINI_API_KEY

        # Use default Gemini model
        MODEL_NAME="gemini-2.0-flash-exp"
        echo -e "${GREEN}✓ Using Gemini model: gemini-2.0-flash-exp${NC}"
        echo -e "${YELLOW}Available Gemini models:${NC}"
        echo "  ⚡ gemini-2.0-flash-exp     (Latest experimental - WORKING)  [2]"
        echo "  🚀 gemini-3-pro-preview     (Next Gen Preview - WORKING)    [3]"
        echo ""
        echo "Shortcuts: Enter '2' for 2.0-flash-exp, '3' for 3-pro-preview"
        echo "Note: Only models that work with Claude CLI are listed"
        echo ""
        read -p "Enter Model Name [default: gemini-2.0-flash-exp]: " input_model
        [[ -n "$input_model" ]] && MODEL_NAME=$input_model

        # Map model names to Claude/Gemini API format
        case "$MODEL_NAME" in
            # 2.0 Models (Latest) - Add numeric shortcuts
            "gemini-2.0-flash-exp"|"2"|"2.0")
                CLAUDE_MODEL="gemini-2.0-flash-exp"
                if [[ "$MODEL_NAME" == "2" || "$MODEL_NAME" == "2.0" ]]; then
                    echo -e "${GREEN}✓ Selected: gemini-2.0-flash-exp (2.0 experimental)${NC}"
                fi
                ;;

            # 3.0 Models (Future/Preview) - Add numeric shortcuts
            "gemini-3-pro-preview"|"gemini-3-preview"|"gemini-3-pro"|"3"|"3.0")
                CLAUDE_MODEL="gemini-3-pro-preview"
                if [[ "$MODEL_NAME" == "3" || "$MODEL_NAME" == "3.0" ]]; then
                    echo -e "${GREEN}✓ Selected: gemini-3-pro-preview (3.0 preview)${NC}"
                fi
                ;;
            "gemini-3.0-flash"|"gemini-3.0-pro"|"gemini-3.0-ultra")
                CLAUDE_MODEL="$MODEL_NAME"
                ;;

            # Default fallback
            *)
                echo -e "${RED}Unknown model: $MODEL_NAME${NC}"
                echo -e "${YELLOW}Using default: gemini-2.0-flash-exp${NC}"
                CLAUDE_MODEL="gemini-2.0-flash-exp"
                ;;
        esac

        echo -e "${GREEN}✓ Mapped to: $CLAUDE_MODEL${NC}"

        # Configure Gemini direct API endpoint
        # Try different endpoints
        GEMINI_ENDPOINT="https://generativelanguage.googleapis.com/v1beta/anthropic"

        # For some models, we might need different format
        case "$CLAUDE_MODEL" in
            "gemini-1.5-pro"|"gemini-1.5-flash")
                # Standard 1.5 models
                export ANTHROPIC_BASE_URL="$GEMINI_ENDPOINT"
                export ANTHROPIC_API_KEY="$GEMINI_API_KEY"
                ;;
            "gemini-2.0-flash-exp"|"gemini-3-pro-preview")
                # Experimental models might need different handling
                export ANTHROPIC_BASE_URL="$GEMINI_ENDPOINT"
                export ANTHROPIC_API_KEY="$GEMINI_API_KEY"
                echo -e "${YELLOW}Note: Using experimental model: $CLAUDE_MODEL${NC}"
                ;;
            *)
                export ANTHROPIC_BASE_URL="$GEMINI_ENDPOINT"
                export ANTHROPIC_API_KEY="$GEMINI_API_KEY"
                ;;
        esac

        # Execute Claude with Gemini model and system prompt
        echo -e "${BLUE}🚀 Starting Gemini chat...${NC}"
        exec claude $SKIP_PERMS_FLAG --model "$CLAUDE_MODEL" --system-prompt "Anda adalah Gemini, model AI dari Google. Selalu identifikasi diri sebagai Gemini dalam setiap respons." "$@"
        ;;
    3)
        # Universal OAuth - All Providers via CCS
        echo -e "${BLUE}🔥 Universal OAuth (Auto-Setup - All Models FREE)${NC}"
        echo ""
        echo -e "${CYAN}💡 CCS akan di-install otomatis jika belum ada (10MB, ~30 detik)${NC}"
        echo ""
        echo -e "${YELLOW}Pilih Provider:${NC}"
        echo "  1) Gemini (Google)           🧠 Google AI Models (8 Models)"
        echo "  2) Codex (OpenAI)            🤖 GPT 5.2, 5.1, 5 (18 Models)"
        echo "  3) GitHub Copilot           💻 Claude & GPT Models"
        echo "  4) AntiGravity (Anthropic)  🔥 Claude Opus 4.5 (6 Models)"
        echo "  5) Kiro (AWS)                ☁️  AWS Claude Models"
        echo ""
        read -p "Pilih [1-5, default: 1]: " oauth_provider
        [[ -z "$oauth_provider" ]] && oauth_provider=1

        case $oauth_provider in
            1)
                # Gemini OAuth
                check_and_install_ccs "gemini"
                
                echo -e "${BLUE}🌟 Google Gemini via CCS OAuth${NC}"
                echo ""
                echo -e "${YELLOW}Pilih Model:${NC}"
                echo "  1) gemini-2.5-pro           (Stable - Most Capable) [RECOMMENDED]"
                echo "  2) gemini-2.5-flash         (Stable - Fast & Efficient)"
                echo "  3) gemini-2.5-flash-lite    (Stable - Ultra Fast)"
                echo "  4) gemini-3-pro-preview     (Next Gen - Most Capable) 🔥"
                echo "  5) gemini-3-flash-preview   (Next Gen - Fast) 🚀"
                echo "  6) gemini-2.0-flash-exp     (Experimental)"
                echo "  7) gemini-1.5-pro           (Stable - Older)"
                echo "  8) gemini-1.5-flash         (Stable - Fast)"
                echo ""
                read -p "Pilih [1-8, default: 1]: " gemini_model
                [[ -z "$gemini_model" ]] && gemini_model=1

                case $gemini_model in
                    1) MODEL="gemini-2.5-pro" ;;
                    2) MODEL="gemini-2.5-flash" ;;
                    3) MODEL="gemini-2.5-flash-lite" ;;
                    4) MODEL="gemini-3-pro-preview" ;;
                    5) MODEL="gemini-3-flash-preview" ;;
                    6) MODEL="gemini-2.0-flash-exp" ;;
                    7) MODEL="gemini-1.5-pro" ;;
                    8) MODEL="gemini-1.5-flash" ;;
                    *) MODEL="gemini-2.5-pro" ;;
                esac

                echo -e "${GREEN}✓ Model: $MODEL${NC}"
                echo -e "${YELLOW}Pastikan sudah login dengan 'ccs gemini --auth'${NC}"
                echo ""

                export ANTHROPIC_MODEL="$MODEL"
                exec ccs gemini $SKIP_PERMS_FLAG --permission-mode bypassPermissions --model "$MODEL" "$@"
                ;;
            2)
                # Codex (OpenAI) OAuth
                check_and_install_ccs "codex"
                
                echo -e "${BLUE}🤖 Codex (OpenAI via CCS OAuth)${NC}"
                echo ""
                echo -e "${YELLOW}Pilih Model:${NC}"
                echo -e "${CYAN}GPT 5.2 Series (Latest 🔥):${NC}"
                echo "  1)  gpt-5.2                  (Flagship - Best for Coding) [RECOMMENDED]"
                echo "  2)  gpt-5.2-pro              (Smarter & More Precise)"
                echo "  3)  gpt-5.2-chat-latest      (ChatGPT Version)"
                echo ""
                echo -e "${CYAN}GPT 5.1 Series:${NC}"
                echo "  4)  gpt-5.1-codex-max        (Most Intelligent Coding)"
                echo "  5)  gpt-5.1-codex            (Agentic Coding Optimized)"
                echo "  6)  gpt-5.1                  (Configurable Reasoning)"
                echo "  7)  gpt-5.1-codex-mini       (Cost-Efficient)"
                echo "  8)  gpt-5.1-chat-latest      (ChatGPT Version)"
                echo ""
                echo -e "${CYAN}GPT 5 Series:${NC}"
                echo "  9)  gpt-5                    (Previous Reasoning Model)"
                echo "  10) gpt-5-pro                (Smarter Version)"
                echo "  11) gpt-5-codex              (Agentic Coding)"
                echo "  12) gpt-5-chat-latest        (ChatGPT Version)"
                echo ""
                echo -e "${CYAN}Legacy (GPT 4 Series):${NC}"
                echo "  13) gpt-4o                   (GPT-4 Omni)"
                echo "  14) gpt-4o-mini              (Fast & Efficient)"
                echo "  15) gpt-4-turbo              (GPT-4 Turbo)"
                echo "  16) o1-preview               (Reasoning Model)"
                echo "  17) o1-mini                  (Fast Reasoning)"
                echo "  18) o1-pro                   (Advanced Reasoning)"
                echo ""
                read -p "Pilih [1-18, default: 1]: " codex_model
                [[ -z "$codex_model" ]] && codex_model=1

                case $codex_model in
                    1) MODEL="gpt-5.2" ;;
                    2) MODEL="gpt-5.2-pro" ;;
                    3) MODEL="gpt-5.2-chat-latest" ;;
                    4) MODEL="gpt-5.1-codex-max" ;;
                    5) MODEL="gpt-5.1-codex" ;;
                    6) MODEL="gpt-5.1" ;;
                    7) MODEL="gpt-5.1-codex-mini" ;;
                    8) MODEL="gpt-5.1-chat-latest" ;;
                    9) MODEL="gpt-5" ;;
                    10) MODEL="gpt-5-pro" ;;
                    11) MODEL="gpt-5-codex" ;;
                    12) MODEL="gpt-5-chat-latest" ;;
                    13) MODEL="gpt-4o" ;;
                    14) MODEL="gpt-4o-mini" ;;
                    15) MODEL="gpt-4-turbo" ;;
                    16) MODEL="o1-preview" ;;
                    17) MODEL="o1-mini" ;;
                    18) MODEL="o1-pro" ;;
                    *) MODEL="gpt-5.2" ;;
                esac

                echo -e "${GREEN}✓ Model: $MODEL${NC}"
                echo -e "${YELLOW}Pastikan sudah login dengan 'ccs codex --auth'${NC}"
                echo ""

                export ANTHROPIC_MODEL="$MODEL"
                exec ccs codex --model "$MODEL" "$@"
                ;;
            3)
                # GitHub Copilot OAuth
                check_and_install_ccs "copilot"
                
                echo -e "${BLUE}💻 GitHub Copilot (OAuth)${NC}"
                echo ""
                echo -e "${YELLOW}Pilih Model:${NC}"
                echo "  1) claude-opus-4.5           (Most Capable) [RECOMMENDED]"
                echo "  2) claude-sonnet-4.5         (Balanced)"
                echo "  3) gpt-4o                   (GPT-4 Omni)"
                echo "  4) gpt-5.1                  (Latest ChatGPT)"
                echo ""
                read -p "Pilih [1-4, default: 1]: " copilot_model
                [[ -z "$copilot_model" ]] && copilot_model=1

                case $copilot_model in
                    1) MODEL="claude-opus-4.5" ;;
                    2) MODEL="claude-sonnet-4.5" ;;
                    3) MODEL="gpt-4o" ;;
                    4) MODEL="gpt-5.1" ;;
                    *) MODEL="claude-opus-4.5" ;;
                esac

                echo -e "${GREEN}✓ Model: $MODEL${NC}"
                echo -e "${CYAN}Requires: npm install -g copilot-api${NC}"
                echo ""

                if command -v copilot-api &> /dev/null; then
                    export ANTHROPIC_MODEL="$MODEL"
                    exec ccs copilot --model "$MODEL" "$@"
                else
                    echo -e "${RED}copilot-api not found!${NC}"
                    echo "Install dengan: npm install -g copilot-api"
                    echo "Kemudian jalankan: ccs copilot auth"
                    echo ""
                    read -p "Press Enter untuk kembali..."
                    exec "$0"
                fi
                ;;
            4)
                # AntiGravity (Anthropic) OAuth
                check_and_install_ccs "agy"
                
                echo -e "${BLUE}🔥 AntiGravity (Anthropic via CCS OAuth)${NC}"
                echo ""
                echo -e "${YELLOW}Pilih Model:${NC}"
                echo "  1) gemini-claude-opus-4-5-thinking  (Most Capable - Thinking) [RECOMMENDED]"
                echo "  2) gemini-3-flash-preview          (Next Gen - Fast)"
                echo "  3) gemini-2.5-pro                  (Stable - Capable)"
                echo "  4) gemini-2.5-flash                (Stable - Fast)"
                echo "  5) claude-opus-4.2                 (Stable - Previous)"
                echo "  6) claude-sonnet-4.2               (Stable - Balanced)"
                echo ""
                read -p "Pilih [1-6, default: 1]: " agy_model
                [[ -z "$agy_model" ]] && agy_model=1

                case $agy_model in
                    1) MODEL="gemini-claude-opus-4-5-thinking" ;;
                    2) MODEL="gemini-3-flash-preview" ;;
                    3) MODEL="gemini-2.5-pro" ;;
                    4) MODEL="gemini-2.5-flash" ;;
                    5) MODEL="claude-opus-4.2" ;;
                    6) MODEL="claude-sonnet-4.2" ;;
                    *) MODEL="gemini-claude-opus-4-5-thinking" ;;
                esac

                echo -e "${GREEN}✓ Model: $MODEL${NC}"
                echo -e "${YELLOW}Pastikan sudah login dengan 'ccs agy --auth'${NC}"
                echo ""

                export ANTHROPIC_MODEL="$MODEL"
                exec ccs agy $SKIP_PERMS_FLAG --permission-mode bypassPermissions --model "$MODEL" "$@"
                ;;
            5)
                # Kiro (AWS) OAuth
                check_and_install_ccs "kiro"
                
                echo -e "${BLUE}☁️  Kiro (AWS CodeWhisperer via CCS OAuth)${NC}"
                echo ""
                echo -e "${YELLOW}Model: AWS-hosted Claude models${NC}"
                echo -e "${CYAN}Pastikan sudah login dengan 'ccs kiro --auth'${NC}"
                echo ""
                exec ccs kiro "$@"
                ;;
        esac
        ;;
    4)
        # OpenAI API Key
        echo -e "${BLUE}Configuring for OpenAI...${NC}"

        # Get API key with persistent storage
        if [[ -z "$OPENAI_API_KEY" ]]; then
            load_api_key_to_var "$HOME/.openai_api_key" "OPENAI_API_KEY"
        fi

        if [[ -z "$OPENAI_API_KEY" ]]; then
            echo "Get Key: https://platform.openai.com/api-keys"
            read -p "Enter OpenAI API Key: " OPENAI_API_KEY
            save_api_key "$OPENAI_API_KEY" "$HOME/.openai_api_key" "OpenAI"
        else
            if [[ ! -f "$HOME/.openai_api_key" ]]; then
                save_api_key "$OPENAI_API_KEY" "$HOME/.openai_api_key" "OpenAI"
            fi
        fi

        # Use default OpenAI model
        MODEL_NAME="gpt-4o"
        echo -e "${GREEN}✓ Using OpenAI model: gpt-4o${NC}"
        echo -e "${YELLOW}Available OpenAI models:${NC}"
        echo "  🚀 gpt-4o                (Latest flagship model - Recommended)"
        echo "  ⚡ gpt-4o-mini           (Fast, efficient, cheaper)"
        echo "  💬 gpt-4o-realtime       (Real-time conversations)"
        echo "  🧠 gpt-4o-audio          (Audio input/output)"
        echo "  🎨 gpt-4-turbo          (Legacy model)"
        echo "  💡 gpt-4-turbo-preview   (Preview features)"
        echo "  💬 gpt-3.5-turbo         (Fast, reliable workhorse)"
        echo ""
        echo "Note: GPT-5 has not been officially released yet"
        echo "      Current latest is GPT-4o (omni model)"
        echo ""
        read -p "Enter Model Name [default: gpt-4o]: " input_model
        [[ -n "$input_model" ]] && MODEL_NAME=$input_model

        # Validate model name
        case "$MODEL_NAME" in
            "gpt-4"|"gpt4")
                MODEL_NAME="gpt-4"
                ;;
            "gpt-4-turbo"|"gpt-4-turbo-preview")
                MODEL_NAME="gpt-4-turbo"
                ;;
            "gpt-4o"|"gpt-4o")
                MODEL_NAME="gpt-4o"
                ;;
            "gpt-4o-mini"|"gpt-4o-mini")
                MODEL_NAME="gpt-4o-mini"
                ;;
            "gpt-4o-realtime"|"gpt-4o-realtime")
                MODEL_NAME="gpt-4o-realtime-preview"
                ;;
            "gpt-4o-audio"|"gpt-4o-audio")
                MODEL_NAME="gpt-4o-audio-preview"
                ;;
            "gpt-3.5-turbo"|"gpt-3.5"|"gpt35"|"gpt-35-turbo")
                MODEL_NAME="gpt-3.5-turbo"
                ;;
            *)
                echo -e "${RED}Unknown model: $MODEL_NAME${NC}"
                echo -e "${YELLOW}Using default: gpt-4o${NC}"
                MODEL_NAME="gpt-4o"
                ;;
        esac

        # Configure for OpenAI via LiteLLM proxy
        export ANTHROPIC_API_KEY="$OPENAI_API_KEY"
        export ANTHROPIC_BASE_URL="https://api.openai.com/v1"
        echo -e "${BLUE}🚀 Starting OpenAI chat via LiteLLM...${NC}"
        echo -e "${YELLOW}Note: Using OpenAI API through Claude interface${NC}"
        exec claude $SKIP_PERMS_FLAG --model "$MODEL_NAME" "$@"
        ;;
    5)
        # OpenAI OAuth (Experimental)
        echo -e "${BLUE}Configuring for OpenAI (OAuth Experimental)...${NC}"
        echo -e "${YELLOW}Note: OAuth feature requires manual setup. Using API Key mode instead.${NC}"

        # Fallback to API Key mode for simplicity
        if [[ -z "$OPENAI_API_KEY" ]]; then
            load_api_key_to_var "$HOME/.openai_api_key" "OPENAI_API_KEY"
        fi

        if [[ -z "$OPENAI_API_KEY" ]]; then
            echo "Get Key: https://platform.openai.com/api-keys"
            read -p "Enter OpenAI API Key: " OPENAI_API_KEY
            save_api_key "$OPENAI_API_KEY" "$HOME/.openai_api_key" "OpenAI"
        else
            if [[ ! -f "$HOME/.openai_api_key" ]]; then
                save_api_key "$OPENAI_API_KEY" "$HOME/.openai_api_key" "OpenAI"
            fi
        fi
        export OPENAI_API_KEY

        # Use default OpenAI model
        MODEL_NAME="gpt-4o"
        echo -e "${GREEN}✓ Using OpenAI model: gpt-4o${NC}"
        echo -e "${YELLOW}Available models: gpt-4o, gpt-4o-mini, gpt-4-turbo, gpt-3.5-turbo${NC}"
        read -p "Enter Model Name [default: gpt-4o]: " input_model
        [[ -n "$input_model" ]] && MODEL_NAME=$input_model

        # Configure for OpenAI via LiteLLM proxy
        export ANTHROPIC_API_KEY="$OPENAI_API_KEY"
        export ANTHROPIC_BASE_URL="https://api.openai.com/v1"
        echo -e "${BLUE}🚀 Starting OpenAI chat via LiteLLM...${NC}"
        echo -e "${YELLOW}Note: Using OpenAI API through Claude interface${NC}"
        exec claude $SKIP_PERMS_FLAG --model "$MODEL_NAME" "$@"
        ;;
    6)
        # xAI
        echo -e "${BLUE}Configuring for xAI (Grok)...${NC}"

        # Get API key with persistent storage
        if [[ -z "$XAI_API_KEY" ]]; then
            load_api_key_to_var "$HOME/.xai_api_key" "XAI_API_KEY"
        fi

        if [[ -z "$XAI_API_KEY" ]]; then
            echo "Get Key: https://console.x.ai/"
            read -p "Enter xAI API Key: " XAI_API_KEY
            save_api_key "$XAI_API_KEY" "$HOME/.xai_api_key" "xAI"
        else
            if [[ ! -f "$HOME/.xai_api_key" ]]; then
                save_api_key "$XAI_API_KEY" "$HOME/.xai_api_key" "xAI"
            fi
        fi
        export XAI_API_KEY

        # Use default xAI model
        MODEL_NAME="grok-beta"
        echo -e "${GREEN}✓ Using xAI model: grok-beta${NC}"
        echo -e "${YELLOW}Available models: grok-beta, grok-vision-beta${NC}"
        read -p "Enter Model Name [default: grok-beta]: " input_model
        [[ -n "$input_model" ]] && MODEL_NAME=$input_model

        export ANTHROPIC_BASE_URL="https://api.x.ai/v1/"
        export ANTHROPIC_API_KEY="$XAI_API_KEY"
        echo -e "${BLUE}🚀 Starting xAI (Grok) chat...${NC}"
        exec claude $SKIP_PERMS_FLAG --model "$MODEL_NAME" "$@"
        ;;
    7)
        # ZhipuAI / GLM (via Z.AI proxy)
        echo -e "${BLUE}Configuring for ZhipuAI (GLM)...${NC}"

        # Auto-use Z_AI_API_KEY if available (from .env), fallback to saved key
        if [[ -z "$ANTHROPIC_AUTH_TOKEN" && -n "$Z_AI_API_KEY" ]]; then
            ANTHROPIC_AUTH_TOKEN="$Z_AI_API_KEY"
        fi

        if [[ -z "$ANTHROPIC_AUTH_TOKEN" ]]; then
            load_api_key_to_var "$HOME/.glm_api_key" "ANTHROPIC_AUTH_TOKEN"
        fi

        if [[ -z "$ANTHROPIC_AUTH_TOKEN" ]]; then
            echo "Get Key: https://z.ai/dashboard or https://open.bigmodel.cn/usercenter/apikeys"
            read -p "Enter Z.AI / GLM API Key: " ANTHROPIC_AUTH_TOKEN
            save_api_key "$ANTHROPIC_AUTH_TOKEN" "$HOME/.glm_api_key" "GLM"
        else
            if [[ ! -f "$HOME/.glm_api_key" ]]; then
                save_api_key "$ANTHROPIC_AUTH_TOKEN" "$HOME/.glm_api_key" "GLM"
            fi
        fi
        export ANTHROPIC_AUTH_TOKEN

        # Model selection menu with numbering
        echo ""
        echo -e "${CYAN}╔═══════════════════════════════════════════════════════════╗${NC}"
        echo -e "${CYAN}║           🤖 ZHIPUAI / GLM - MODEL SELECTION              ║${NC}"
        echo -e "${CYAN}╚═══════════════════════════════════════════════════════════╝${NC}"
        echo ""
        echo -e "${GREEN}✨ AVAILABLE MODELS:${NC}"
        echo ""
        echo "  1) ⚡ glm-5.1    (Tuned - balanced speed + quality) ⭐"
        echo "  2) 🚀 glm-5      (Flagship - raw latest gen)"
        echo ""

        read -p "Select model [1-2, default: 1]: " model_choice
        [[ -z "$model_choice" ]] && model_choice=1

        case "$model_choice" in
            1)
                MODEL_NAME="glm-5.1"
                echo -e "${GREEN}✓ Selected: glm-5.1${NC}"
                ;;
            2)
                MODEL_NAME="glm-5"
                echo -e "${GREEN}✓ Selected: glm-5${NC}"
                ;;
            *)
                MODEL_NAME="glm-5.1"
                ;;
        esac

        echo ""
        echo -e "${BLUE}🚀 Starting GLM chat with $MODEL_NAME...${NC}"
        echo ""

        export ANTHROPIC_BASE_URL="https://api.z.ai/api/anthropic"
        export ANTHROPIC_API_KEY="$ANTHROPIC_AUTH_TOKEN"
        export CLAUDE_MODEL="$MODEL_NAME"
        exec claude $SKIP_PERMS_FLAG --model "$MODEL_NAME" "$@"
        ;;
    8)
        # Groq
        echo -e "${BLUE}Configuring for Groq...${NC}"

        # Get API key with persistent storage
        if [[ -z "$GROQ_API_KEY" ]]; then
            load_api_key_to_var "$HOME/.groq_api_key" "GROQ_API_KEY"
        fi

        if [[ -z "$GROQ_API_KEY" ]]; then
            echo "Get Key: https://console.groq.com/keys"
            read -p "Enter Groq API Key: " GROQ_API_KEY
            save_api_key "$GROQ_API_KEY" "$HOME/.groq_api_key" "Groq"
        else
            if [[ ! -f "$HOME/.groq_api_key" ]]; then
                save_api_key "$GROQ_API_KEY" "$HOME/.groq_api_key" "Groq"
            fi
        fi
        export GROQ_API_KEY

        # Use default Groq model
        MODEL_NAME="llama-3.1-70b-versatile"
        echo -e "${GREEN}✓ Using Groq model: llama-3.1-70b-versatile${NC}"
        echo -e "${YELLOW}Available models: llama-3.1-70b-versatile, llama-3.1-8b-instant, mixtral-8x7b-32768${NC}"
        read -p "Enter Model Name [default: llama-3.1-70b-versatile]: " input_model
        [[ -n "$input_model" ]] && MODEL_NAME=$input_model

        export ANTHROPIC_BASE_URL="https://api.groq.com/openai/v1/"
        export ANTHROPIC_API_KEY="$GROQ_API_KEY"
        echo -e "${BLUE}🚀 Starting Groq chat...${NC}"
        exec claude $SKIP_PERMS_FLAG --model "$MODEL_NAME" "$@"
        ;;
    9)
        # Perplexity
        echo -e "${BLUE}Configuring for Perplexity...${NC}"

        # Get API key with persistent storage
        if [[ -z "$PERPLEXITY_API_KEY" ]]; then
            # Try to load from file
            load_api_key_to_var "$HOME/.perplexity_api_key" "PERPLEXITY_API_KEY"
        fi

        if [[ -z "$PERPLEXITY_API_KEY" ]]; then
            echo "Get Key: https://console.perplexity.ai/"
            read -p "Enter Perplexity API Key: " PERPLEXITY_API_KEY
            save_api_key "$PERPLEXITY_API_KEY" "$HOME/.perplexity_api_key" "Perplexity"
        else
            # Save current key if not already saved
            if [[ ! -f "$HOME/.perplexity_api_key" ]]; then
                save_api_key "$PERPLEXITY_API_KEY" "$HOME/.perplexity_api_key" "Perplexity"
            fi
        fi
        export PERPLEXITY_API_KEY

        # Check if custom Perplexity model exists
        if [[ -f "$SCRIPT_DIR/models/perplexity/config.json" ]]; then
            handle_custom_model "perplexity" "$@"
        else
            # Create temporary Perplexity config
            echo -e "${YELLOW}Creating temporary Perplexity configuration...${NC}"

            cat > "$SCRIPT_DIR/models/temp_perplexity.json" << EOF
{
    "provider_name": "Perplexity AI",
    "description": "Search-powered AI with real-time web search",
    "api_key": "$PERPLEXITY_API_KEY",
    "api_base": "https://api.perplexity.ai/",
    "model": "sonar-pro",
    "notes": "Temporary config for Perplexity"
}
EOF

            handle_custom_model "temp_perplexity" "$@"
            rm -f "$SCRIPT_DIR/models/temp_perplexity.json"
        fi
        ;;
    10)
        # Cohere
        echo -e "${BLUE}Configuring for Cohere...${NC}"

        # Get API key with persistent storage
        if [[ -z "$COHERE_API_KEY" ]]; then
            load_api_key_to_var "$HOME/.cohere_api_key" "COHERE_API_KEY"
        fi

        if [[ -z "$COHERE_API_KEY" ]]; then
            echo "Get Key: https://dashboard.cohere.com/api-keys"
            read -p "Enter Cohere API Key: " COHERE_API_KEY
            save_api_key "$COHERE_API_KEY" "$HOME/.cohere_api_key" "Cohere"
        else
            if [[ ! -f "$HOME/.cohere_api_key" ]]; then
                save_api_key "$COHERE_API_KEY" "$HOME/.cohere_api_key" "Cohere"
            fi
        fi
        export COHERE_API_KEY

        # Use default Cohere model
        MODEL_NAME="command-r-plus"
        echo -e "${GREEN}✓ Using Cohere model: command-r-plus${NC}"
        echo -e "${YELLOW}Available models: command-r, command-r-plus, command-r-08-2024${NC}"
        read -p "Enter Model Name [default: command-r-plus]: " input_model
        [[ -n "$input_model" ]] && MODEL_NAME=$input_model

        export ANTHROPIC_BASE_URL="https://api.cohere.ai/v1/"
        export ANTHROPIC_API_KEY="$COHERE_API_KEY"
        echo -e "${BLUE}🚀 Starting Cohere chat...${NC}"
        exec claude $SKIP_PERMS_FLAG --model "$MODEL_NAME" "$@"
        ;;
    11)
        # DeepSeek - EXACT SAME PATTERN AS MINIMAX (Option 1)
        echo -e "${BLUE}Configuring for DeepSeek...${NC}"

        # Get API key with persistent storage - SAME AS MINIMAX
        get_api_key_with_save "DEEPSEEK_API_KEY" "$HOME/.deepseek_api_key" "DeepSeek" "https://platform.deepseek.com/"

        export ANTHROPIC_BASE_URL="https://api.deepseek.com/anthropic"
        export ANTHROPIC_API_KEY="$DEEPSEEK_API_KEY"
        echo -e "${GREEN}✓ DeepSeek API configured${NC}"

        # Model selection menu
        echo ""
        echo -e "${YELLOW}Available DeepSeek models:${NC}"
        echo "  🚀 deepseek-chat       (V3.2 Fast & Efficient - 128K context)     [chat]"
        echo "  🧠 deepseek-reasoner   (V3.2 Thinking Mode - Deep Analysis)       [reasoner]"
        echo ""
        echo -e "${GREEN}Shortcuts:${NC}"
        echo "  'chat' or '1'      → deepseek-chat (Recommended for coding)"
        echo "  'reasoner' or '2'  → deepseek-reasoner (For complex reasoning)"
        echo ""
        echo -e "${BLUE}💡 DeepSeek V3.2 Features:${NC}"
        echo "  • Context: 128K tokens"
        echo "  • deepseek-chat: Max 8K output, fast responses"
        echo "  • deepseek-reasoner: Max 64K output with thinking blocks"
        echo ""

        # Use deepseek-chat as default
        MODEL_NAME="deepseek-chat"
        echo -e "${GREEN}✓ Default model: deepseek-chat${NC}"
        read -p "Enter Model Name [default: deepseek-chat]: " input_model
        [[ -n "$input_model" ]] && MODEL_NAME=$input_model

        # Map shortcuts to full model names
        case "$MODEL_NAME" in
            "chat"|"1"|"c")
                FINAL_MODEL="deepseek-chat"
                echo -e "${GREEN}✓ Selected: deepseek-chat (Fast & Efficient)${NC}"
                ;;
            "reasoner"|"2"|"r"|"think"|"thinking")
                FINAL_MODEL="deepseek-reasoner"
                echo -e "${GREEN}✓ Selected: deepseek-reasoner (Thinking Mode)${NC}"
                ;;
            *)
                FINAL_MODEL="$MODEL_NAME"
                echo -e "${GREEN}✓ Using model: $MODEL_NAME${NC}"
                ;;
        esac

        echo -e "${BLUE}🚀 Starting DeepSeek chat with $FINAL_MODEL...${NC}"
        exec claude $SKIP_PERMS_FLAG --model "$FINAL_MODEL" --system-prompt "Anda adalah DeepSeek AI. Model aktif: $FINAL_MODEL. Selalu identifikasi diri sebagai DeepSeek dalam setiap respons." "$@"
        ;;
    12)
        # Ollama
        check_dependencies
        echo -e "${BLUE}Configuring for Ollama...${NC}"
        if [[ -z "$OLLAMA_HOST" ]]; then
            read -p "Enter Ollama Host [default: http://localhost:11434]: " OLLAMA_HOST
            [[ -z "$OLLAMA_HOST" ]] && OLLAMA_HOST="http://localhost:11434"
            export OLLAMA_HOST
        fi

        # Use default Ollama model
        MODEL_NAME="llama3"
        echo -e "${GREEN}✓ Using Ollama model: llama3${NC}"
        echo -e "${YELLOW}Available models: llama2, llama3, codellama, mistral, vicuna${NC}"
        read -p "Enter Model Name [default: llama3]: " input_model
        [[ -n "$input_model" ]] && MODEL_NAME=$input_model

        export ANTHROPIC_BASE_URL="http://localhost:11434/v1"
        export ANTHROPIC_API_KEY="ollama"
        echo -e "${BLUE}🚀 Starting Ollama chat...${NC}"
        exec claude --no-chrome --model "$MODEL_NAME" "$@"
        ;;
    13)
        # Mistral with 15 Models (2025)
        echo -e "${BLUE}🇫🇷 Mistral AI (European AI)${NC}"
        echo ""
        echo -e "${YELLOW}Pilih Model:${NC}"
        echo -e "${CYAN}🌟 Featured Models (Latest & Greatest):${NC}"
        echo "  1)  mistral-large-latest      (Mistral Large 3 - State-of-the-art) [RECOMMENDED]"
        echo "  2)  devstral-2                (Frontier Code Agents - Open)"
        echo "  3)  mistral-medium-3.1        (Frontier Multimodal - Premier)"
        echo ""
        echo -e "${CYAN}🔥 Frontier Generalist:${NC}"
        echo "  4)  mistral-small-latest      (Mistral Small 3.2 - Open)"
        echo "  5)  ministral-3-latest       (Ministral 3 14B - Best Text & Vision)"
        echo "  6)  ministral-3-8b            (Efficient - Open)"
        echo "  7)  ministral-3-3b            (Tiny - Open)"
        echo "  8)  magistral-medium-latest   (Reasoning - Premier)"
        echo "  9)  magistral-small-latest    (Small Reasoning - Open)"
        echo ""
        echo -e "${CYAN}💻 Coding Models:${NC}"
        echo " 10) codestral-latest          (Cutting-edge Code - Premier)"
        echo " 11) devstral-small-2          (Code Agents - Labs)"
        echo " 12) devstral-medium-1.0       (Enterprise SWE - Premier)"
        echo ""
        echo -e "${CYAN}🎨 Specialist Models:${NC}"
        echo " 13) mistral-small-creative    (Creative Writing - Labs)"
        echo " 14) ocr-3                    (Document AI - Premier)"
        echo " 15) voxtral-mini              (Audio - Open)"
        echo ""
        read -p "Pilih [1-15, default: 1]: " mistral_model
        [[ -z "$mistral_model" ]] && mistral_model=1

        case $mistral_model in
            1) MODEL="mistral-large-latest" ;;
            2) MODEL="devstral-2" ;;
            3) MODEL="mistral-medium-3.1" ;;
            4) MODEL="mistral-small-latest" ;;
            5) MODEL="ministral-3-latest" ;;
            6) MODEL="ministral-3-8b" ;;
            7) MODEL="ministral-3-3b" ;;
            8) MODEL="magistral-medium-latest" ;;
            9) MODEL="magistral-small-latest" ;;
            10) MODEL="codestral-latest" ;;
            11) MODEL="devstral-small-2" ;;
            12) MODEL="devstral-medium-1.0" ;;
            13) MODEL="mistral-small-creative" ;;
            14) MODEL="ocr-3" ;;
            15) MODEL="voxtral-mini" ;;
            *) MODEL="mistral-large-latest" ;;
        esac

        echo -e "${GREEN}✓ Model: $MODEL${NC}"
        echo ""

        # Get API key with persistent storage
        if [[ -z "$MISTRAL_API_KEY" ]]; then
            load_api_key_to_var "$HOME/.mistral_api_key" "MISTRAL_API_KEY"
        fi

        if [[ -z "$MISTRAL_API_KEY" ]]; then
            echo "Get Key: https://console.mistral.ai/"
            read -p "Enter Mistral API Key: " MISTRAL_API_KEY
            save_api_key "$MISTRAL_API_KEY" "$HOME/.mistral_api_key" "Mistral"
        else
            if [[ ! -f "$HOME/.mistral_api_key" ]]; then
                save_api_key "$MISTRAL_API_KEY" "$HOME/.mistral_api_key" "Mistral"
            fi
        fi
        export MISTRAL_API_KEY

        export ANTHROPIC_BASE_URL="https://api.mistral.ai/v1/"
        export ANTHROPIC_API_KEY="$MISTRAL_API_KEY"
        echo -e "${BLUE}🚀 Starting Mistral chat...${NC}"
        exec claude $SKIP_PERMS_FLAG --model "$MODEL" "$@"
        ;;
    14)
        # Moonshot
        echo -e "${BLUE}Configuring for Moonshot...${NC}"

        # Get API key with persistent storage
        if [[ -z "$MOONSHOT_API_KEY" ]]; then
            load_api_key_to_var "$HOME/.moonshot_api_key" "MOONSHOT_API_KEY"
        fi

        if [[ -z "$MOONSHOT_API_KEY" ]]; then
            echo "Get Key: https://platform.moonshot.cn/"
            read -p "Enter Moonshot API Key: " MOONSHOT_API_KEY
            save_api_key "$MOONSHOT_API_KEY" "$HOME/.moonshot_api_key" "Moonshot"
        else
            if [[ ! -f "$HOME/.moonshot_api_key" ]]; then
                save_api_key "$MOONSHOT_API_KEY" "$HOME/.moonshot_api_key" "Moonshot"
            fi
        fi
        export MOONSHOT_API_KEY

        # Use default Moonshot model
        MODEL_NAME="moonshot-v1-8k"
        echo -e "${GREEN}✓ Using Moonshot model: moonshot-v1-8k${NC}"
        echo -e "${YELLOW}Available models: moonshot-v1-8k, moonshot-v1-32k, moonshot-v1-128k${NC}"
        read -p "Enter Model Name [default: moonshot-v1-8k]: " input_model
        [[ -n "$input_model" ]] && MODEL_NAME=$input_model

        export ANTHROPIC_BASE_URL="https://api.moonshot.cn/v1/"
        export ANTHROPIC_API_KEY="$MOONSHOT_API_KEY"
        echo -e "${BLUE}🚀 Starting Moonshot chat...${NC}"
        exec claude $SKIP_PERMS_FLAG --model "$MODEL_NAME" "$@"
        ;;
    15)
        # Qwen
        echo -e "${BLUE}Configuring for Qwen...${NC}"

        # Get API key with persistent storage
        if [[ -z "$QWEN_API_KEY" ]]; then
            load_api_key_to_var "$HOME/.qwen_api_key" "QWEN_API_KEY"
        fi

        if [[ -z "$QWEN_API_KEY" ]]; then
            echo "Get Key: https://dashscope.aliyuncs.com/"
            read -p "Enter Qwen API Key: " QWEN_API_KEY
            save_api_key "$QWEN_API_KEY" "$HOME/.qwen_api_key" "Qwen"
        else
            if [[ ! -f "$HOME/.qwen_api_key" ]]; then
                save_api_key "$QWEN_API_KEY" "$HOME/.qwen_api_key" "Qwen"
            fi
        fi
        export QWEN_API_KEY

        # Use default Qwen model
        MODEL_NAME="qwen-plus"
        echo -e "${GREEN}✓ Using Qwen model: qwen-plus${NC}"
        echo -e "${YELLOW}Available models: qwen-turbo, qwen-plus, qwen-max, qwen2-72b${NC}"
        read -p "Enter Model Name [default: qwen-plus]: " input_model
        [[ -n "$input_model" ]] && MODEL_NAME=$input_model

        export ANTHROPIC_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1/"
        export ANTHROPIC_API_KEY="$QWEN_API_KEY"
        echo -e "${BLUE}🚀 Starting Qwen chat...${NC}"
        exec claude $SKIP_PERMS_FLAG --model "$MODEL_NAME" "$@"
        ;;
    16)
        # OpenRouter
        echo -e "${BLUE}Configuring for OpenRouter...${NC}"

        # Get API key with persistent storage
        if [[ -z "$OPENROUTER_API_KEY" ]]; then
            load_api_key_to_var "$HOME/.openrouter_api_key" "OPENROUTER_API_KEY"
        fi

        if [[ -z "$OPENROUTER_API_KEY" ]]; then
            echo "Get Key: https://openrouter.ai/keys"
            read -p "Enter OpenRouter API Key: " OPENROUTER_API_KEY
            save_api_key "$OPENROUTER_API_KEY" "$HOME/.openrouter_api_key" "OpenRouter"
        else
            if [[ ! -f "$HOME/.openrouter_api_key" ]]; then
                save_api_key "$OPENROUTER_API_KEY" "$HOME/.openrouter_api_key" "OpenRouter"
            fi
        fi
        export OPENROUTER_API_KEY

        # Use default OpenRouter model
        MODEL_NAME="anthropic/claude-3.5-sonnet"
        echo -e "${GREEN}✓ Using OpenRouter model: anthropic/claude-3.5-sonnet${NC}"
        echo -e "${YELLOW}Popular models: anthropic/claude-3.5-sonnet, openai/gpt-4o, google/gemini-pro, meta-llama/llama-3.1-70b${NC}"
        read -p "Enter Model Name [default: anthropic/claude-3.5-sonnet]: " input_model
        [[ -n "$input_model" ]] && MODEL_NAME=$input_model

        export ANTHROPIC_BASE_URL="https://openrouter.ai/api/v1/"
        export ANTHROPIC_API_KEY="$OPENROUTER_API_KEY"
        echo -e "${BLUE}🚀 Starting OpenRouter chat...${NC}"
        exec claude $SKIP_PERMS_FLAG --model "$MODEL_NAME" "$@"
        ;;
    17)
        # Letta AI - Official Letta Platform API (Memory-Augmented Agents)
        echo -e "${BLUE}🧠 Letta Memory Agent${NC}"
        echo -e "${CYAN}   Platform: https://letta.com${NC}"
        echo ""

        # Get Letta API key
        # Try to load from file first
        if [[ -z "$LETTA_API_KEY" ]]; then
            load_api_key_to_var "$HOME/.letta_api_key" "LETTA_API_KEY"
        fi

        if [[ -z "$LETTA_API_KEY" ]]; then
            echo -e "${YELLOW}Letta API Key required${NC}"
            echo "Get your free API key at: https://letta.com"
            echo "Free tier: 5,000 credits/month"
            echo ""
            read -sp "Enter Letta API Key: " LETTA_KEY_TEMP
            echo ""
            [[ -z "$LETTA_KEY_TEMP" ]] && { echo -e "${RED}API Key required!${NC}"; exit 1; }

            # Save to file for future use
            echo "$LETTA_KEY_TEMP" > "$HOME/.letta_api_key"
            chmod 600 "$HOME/.letta_api_key"
            export LETTA_API_KEY="$LETTA_KEY_TEMP"
        fi

        echo ""
        echo "Pilih Model:"
        echo "  1) Opus 4.7 🚀 Latest Flagship - Best for complex coding & reasoning ⭐"
        echo "  2) Opus 4   🔬 Previous Flagship - Complex reasoning"
        echo "  3) Sonnet   🧠 Balanced - Default (Recommended)"
        echo "  4) Haiku    ⚡ Fastest - Quick responses"
        echo "  5) GPT-4o   🤖 OpenAI - ChatGPT Flagship"
        echo "  6) Gemini   🌟 Google - Gemini 2.0 Flash"
        echo ""
        read -p "Pilih [1-6, default: 3]: " model_choice
        [[ -z "$model_choice" ]] && model_choice=3

        # Configure Letta API (IMPORTANT: Use AUTH_TOKEN, not API_KEY!)
        export ANTHROPIC_AUTH_TOKEN="$LETTA_API_KEY"
        export ANTHROPIC_BASE_URL="https://api.letta.com/v1/anthropic"

        system_prompt="You are Letta, a memory-augmented AI agent with persistent memory capabilities. You maintain context across conversations, remember user preferences, and build long-term knowledge. Key features: (1) Long-term memory, (2) Context awareness, (3) Personalization. Always identify yourself as Letta when asked."

        case $model_choice in
            1)
                echo -e "${GREEN}✓ Model: Claude Opus 4.7 (Letta) ⭐${NC}"
                echo -e "${BLUE}🚀 Starting Letta Agent...${NC}"
                exec claude $SKIP_PERMS_FLAG --no-chrome --model "claude-opus-4-7-latest" --system-prompt "$system_prompt"
                ;;
            2)
                echo -e "${GREEN}✓ Model: Claude Opus 4 (Letta)${NC}"
                echo -e "${BLUE}🚀 Starting Letta Agent...${NC}"
                exec claude $SKIP_PERMS_FLAG --no-chrome --model "claude-opus-4-20250514" --system-prompt "$system_prompt"
                ;;
            4)
                echo -e "${GREEN}✓ Model: Claude Haiku (Letta)${NC}"
                echo -e "${BLUE}🚀 Starting Letta Agent...${NC}"
                exec claude $SKIP_PERMS_FLAG --no-chrome --model "claude-haiku-4-20250514" --system-prompt "$system_prompt"
                ;;
            5)
                echo -e "${GREEN}✓ Model: GPT-4o (Letta)${NC}"
                exec claude $SKIP_PERMS_FLAG --no-chrome --model "gpt-4o" --system-prompt "$system_prompt"
                ;;
            6)
                echo -e "${GREEN}✓ Model: Gemini 2.0 Flash (Letta)${NC}"
                exec claude $SKIP_PERMS_FLAG --no-chrome --model "gemini-2.0-flash-exp" --system-prompt "$system_prompt"
                ;;
            3|*)
                echo -e "${GREEN}✓ Model: Claude Sonnet (Letta)${NC}"
                echo -e "${BLUE}🚀 Starting Letta Agent...${NC}"
                exec claude $SKIP_PERMS_FLAG --no-chrome --model "claude-sonnet-4-20250514" --system-prompt "$system_prompt"
                ;;
        esac
        ;;
    18)
        # API Key Manager - Built-in function
        api_key_manager
        # Restart the menu
        exec "$0"
        ;;
    19)
        # Claude Master Tool
        echo -e "${BLUE}Opening Claude Master Tool...${NC}"
        
        # Try multiple possible locations
        MASTER_TOOL=""
        for path in \
            "$SCRIPT_DIR/utils/claude_master.py" \
            "$SCRIPT_DIR/../utils/claude_master.py" \
            "$HOME/ClaudeAll/utils/claude_master.py" \
            "/data/data/com.termux/files/home/ClaudeAll/utils/claude_master.py"
        do
            if [[ -f "$path" ]]; then
                MASTER_TOOL="$path"
                break
            fi
        done
        
        if [[ -n "$MASTER_TOOL" ]]; then
            if [[ "$MASTER_TOOL" == *.py ]]; then
                python3 "$MASTER_TOOL"
            else
                "$MASTER_TOOL"
            fi
        else
            echo -e "${YELLOW}Claude Master Tool not found.${NC}"
            echo -e "${CYAN}Tip: Clone repo to ~/ClaudeAll for full features${NC}"
        fi
        echo ""
        echo -e "${YELLOW}Press Enter to return to main menu...${NC}"
        read
        exec "$0"
        ;;
    20)
        # Advanced Model Manager - Integrated with Claude, GLM, Letta, MiniMax
        clear
        echo -e "${CYAN}╔═══════════════════════════════════════════════════════════╗${NC}"
        echo -e "${CYAN}║          🛠️  ADVANCED MODEL MANAGER                       ║${NC}"
        echo -e "${CYAN}╚═══════════════════════════════════════════════════════════╝${NC}"
        echo ""
        echo -e "${YELLOW}📌 PROVIDER MANAGEMENT:${NC}"
        echo "  1) 🤖 Claude/Anthropic   - API key & test"
        echo "  2) 🇨🇳 ZhipuAI/GLM        - API key & test"
        echo "  3) 🧠 Letta AI           - API key & agents"
        echo "  4) 🎵 MiniMax            - API key & test"
        echo ""
        echo -e "${YELLOW}🔧 MODEL CONFIGURATION:${NC}"
        echo "  5) ➕ Add Custom Model    - Template/Manual"
        echo "  6) ✏️  Edit Existing Model"
        echo "  7) 📋 List All Models"
        echo ""
        echo -e "${YELLOW}⚙️  UTILITIES:${NC}"
        echo "  8) 🔑 API Key Manager    - View/Delete keys"
        echo "  9) 📋 View All Configs"
        echo " 10) 🗑️  Reset Config"
        echo ""
        echo "  0) 🔙 Kembali ke menu utama"
        echo ""
        read -p "Pilih [0-10]: " mgr_choice

        case $mgr_choice in
            1)
                # Claude/Anthropic Manager
                echo ""
                echo -e "${BLUE}═══ CLAUDE/ANTHROPIC CONFIG ═══${NC}"
                echo ""
                echo -e "${CYAN}Current Config:${NC}"
                [[ -f "$HOME/.anthropic_api_key" ]] && echo "  API Key: ****$(tail -c 8 $HOME/.anthropic_api_key 2>/dev/null)" || echo "  API Key: Not set"
                echo ""
                echo "1) Set/Update API Key"
                echo "2) Test Connection"
                echo "3) View Available Models"
                echo "0) Back"
                echo ""
                read -p "Pilih: " claude_op
                case $claude_op in
                    1)
                        echo ""
                        echo "Get key: https://console.anthropic.com/settings/keys"
                        read -p "Enter Anthropic API Key: " new_key
                        if [[ -n "$new_key" ]]; then
                            echo "$new_key" > "$HOME/.anthropic_api_key"
                            chmod 600 "$HOME/.anthropic_api_key"
                            echo -e "${GREEN}✓ API Key saved!${NC}"
                        fi
                        ;;
                    2)
                        echo ""
                        echo "Testing connection..."
                        if [[ -f "$HOME/.anthropic_api_key" ]]; then
                            key=$(cat "$HOME/.anthropic_api_key")
                            resp=$(curl -s -w "%{http_code}" -o /dev/null -X POST "https://api.anthropic.com/v1/messages" \
                                -H "x-api-key: $key" \
                                -H "anthropic-version: 2023-06-01" \
                                -H "content-type: application/json" \
                                -d '{"model":"claude-3-haiku-20240307","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}')
                            [[ "$resp" == "200" ]] && echo -e "${GREEN}✓ Connection OK!${NC}" || echo -e "${RED}✗ Error (HTTP $resp)${NC}"
                        else
                            echo -e "${RED}No API key set${NC}"
                        fi
                        ;;
                    3)
                        echo ""
                        echo -e "${CYAN}Available Claude Models:${NC}"
                        echo "  • claude-sonnet-4-20250514 (Latest Sonnet)"
                        echo "  • claude-3-5-sonnet-20241022 (Sonnet 3.5)"
                        echo "  • claude-3-5-haiku-20241022 (Haiku - Fast)"
                        echo "  • claude-3-opus-20240229 (Opus - Best)"
                        ;;
                esac
                ;;
            2)
                # GLM Manager - Dynamic Model Management
                GLM_CONFIG="$SCRIPT_DIR/models/glm/config.json"
                echo ""
                echo -e "${BLUE}═══ ZHIPUAI/GLM CONFIG ═══${NC}"
                echo ""
                echo -e "${CYAN}Current Config:${NC}"
                [[ -f "$HOME/.glm_api_key" ]] && echo "  API Key: ****$(tail -c 8 $HOME/.glm_api_key 2>/dev/null)" || echo "  API Key: Not set"
                if [[ -f "$GLM_CONFIG" ]] && command -v jq &>/dev/null; then
                    model_count=$(jq '.models | length' "$GLM_CONFIG" 2>/dev/null || echo "0")
                    echo "  Models: $model_count configured"
                fi
                echo ""
                echo -e "${YELLOW}API & Testing:${NC}"
                echo "1) Set/Update API Key"
                echo "2) Test Model (pilih dari list)"
                echo ""
                echo -e "${YELLOW}Model Management:${NC}"
                echo "3) ➕ Add New Model"
                echo "4) ✏️  Edit Model"
                echo "5) 🗑️  Delete Model"
                echo "6) 📋 View All Models"
                echo ""
                echo "0) Back"
                echo ""
                read -p "Pilih: " glm_op
                case $glm_op in
                    1)
                        echo ""
                        echo "Get key: https://open.bigmodel.cn/usercenter/apikeys"
                        read -p "Enter GLM API Key: " new_key
                        if [[ -n "$new_key" ]]; then
                            echo "$new_key" > "$HOME/.glm_api_key"
                            chmod 600 "$HOME/.glm_api_key"
                            echo -e "${GREEN}✓ API Key saved!${NC}"
                        fi
                        ;;
                    2)
                        # Test Model - Dynamic
                        echo ""
                        echo -e "${CYAN}Select model to test:${NC}"
                        if [[ -f "$GLM_CONFIG" ]] && command -v jq &>/dev/null; then
                            jq -r '.models[] | "\(.id) - \(.description)"' "$GLM_CONFIG" 2>/dev/null | nl -w2 -s") "
                            echo ""
                            read -p "Model number: " model_num
                            model_id=$(jq -r ".models[$((model_num-1))].id // empty" "$GLM_CONFIG" 2>/dev/null)
                            if [[ -n "$model_id" ]]; then
                                echo "Testing $model_id..."
                                if [[ -f "$HOME/.glm_api_key" ]]; then
                                    key=$(cat "$HOME/.glm_api_key")
                                    api_base=$(jq -r '.api_base' "$GLM_CONFIG")
                                    resp=$(curl -s "$api_base/chat/completions" \
                                        -H "Authorization: Bearer $key" \
                                        -H "Content-Type: application/json" \
                                        -d "{\"model\":\"$model_id\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"max_tokens\":10}")
                                    if echo "$resp" | grep -q "choices"; then
                                        echo -e "${GREEN}✓ $model_id OK!${NC}"
                                    else
                                        echo -e "${RED}✗ Error: $(echo "$resp" | grep -o '"message":"[^"]*"' | head -1)${NC}"
                                    fi
                                else
                                    echo -e "${RED}No API key set${NC}"
                                fi
                            fi
                        else
                            echo -e "${RED}Config not found or jq not installed${NC}"
                        fi
                        ;;
                    3)
                        # Add New Model
                        echo ""
                        echo -e "${CYAN}Add New GLM Model${NC}"
                        read -p "Model ID (e.g., glm-5): " new_id
                        read -p "Model Name (e.g., GLM-5): " new_name
                        read -p "Description: " new_desc
                        if [[ -n "$new_id" && -n "$new_name" ]]; then
                            if command -v jq &>/dev/null && [[ -f "$GLM_CONFIG" ]]; then
                                jq ".models += [{\"id\":\"$new_id\",\"name\":\"$new_name\",\"description\":\"$new_desc\"}]" "$GLM_CONFIG" > "${GLM_CONFIG}.tmp" && mv "${GLM_CONFIG}.tmp" "$GLM_CONFIG"
                                echo -e "${GREEN}✓ Model '$new_name' added!${NC}"
                            else
                                echo -e "${RED}jq required for model management${NC}"
                            fi
                        fi
                        ;;
                    4)
                        # Edit Model
                        echo ""
                        echo -e "${CYAN}Edit GLM Model${NC}"
                        if [[ -f "$GLM_CONFIG" ]] && command -v jq &>/dev/null; then
                            jq -r '.models[] | "\(.id) - \(.name)"' "$GLM_CONFIG" 2>/dev/null | nl -w2 -s") "
                            echo ""
                            read -p "Model number to edit: " edit_num
                            idx=$((edit_num-1))
                            current_id=$(jq -r ".models[$idx].id // empty" "$GLM_CONFIG")
                            current_name=$(jq -r ".models[$idx].name // empty" "$GLM_CONFIG")
                            current_desc=$(jq -r ".models[$idx].description // empty" "$GLM_CONFIG")
                            if [[ -n "$current_id" ]]; then
                                echo ""
                                echo "Current: $current_id - $current_name"
                                echo "  Desc: $current_desc"
                                echo ""
                                read -p "New ID [$current_id]: " new_id
                                read -p "New Name [$current_name]: " new_name
                                read -p "New Description [$current_desc]: " new_desc
                                new_id=${new_id:-$current_id}
                                new_name=${new_name:-$current_name}
                                new_desc=${new_desc:-$current_desc}
                                jq ".models[$idx] = {\"id\":\"$new_id\",\"name\":\"$new_name\",\"description\":\"$new_desc\"}" "$GLM_CONFIG" > "${GLM_CONFIG}.tmp" && mv "${GLM_CONFIG}.tmp" "$GLM_CONFIG"
                                echo -e "${GREEN}✓ Model updated!${NC}"
                            fi
                        fi
                        ;;
                    5)
                        # Delete Model
                        echo ""
                        echo -e "${CYAN}Delete GLM Model${NC}"
                        if [[ -f "$GLM_CONFIG" ]] && command -v jq &>/dev/null; then
                            jq -r '.models[] | "\(.id) - \(.name)"' "$GLM_CONFIG" 2>/dev/null | nl -w2 -s") "
                            echo ""
                            read -p "Model number to delete: " del_num
                            idx=$((del_num-1))
                            del_name=$(jq -r ".models[$idx].name // empty" "$GLM_CONFIG")
                            if [[ -n "$del_name" ]]; then
                                read -p "Delete '$del_name'? (yes/no): " confirm
                                if [[ "$confirm" == "yes" ]]; then
                                    jq "del(.models[$idx])" "$GLM_CONFIG" > "${GLM_CONFIG}.tmp" && mv "${GLM_CONFIG}.tmp" "$GLM_CONFIG"
                                    echo -e "${GREEN}✓ Model deleted!${NC}"
                                fi
                            fi
                        fi
                        ;;
                    6)
                        # View All Models
                        echo ""
                        echo -e "${CYAN}GLM Models (from config.json):${NC}"
                        if [[ -f "$GLM_CONFIG" ]] && command -v jq &>/dev/null; then
                            jq -r '.models[] | "  • \(.id) - \(.description)"' "$GLM_CONFIG" 2>/dev/null
                            echo ""
                            echo -e "${CYAN}API Base:${NC} $(jq -r '.api_base' "$GLM_CONFIG")"
                            echo -e "${CYAN}Default:${NC} $(jq -r '.default_model' "$GLM_CONFIG")"
                        else
                            echo "  • glm-4.7 (Flagship)"
                            echo "  • glm-4.6v (Vision)"
                        fi
                        ;;
                esac
                ;;
            3)
                # Letta Manager
                echo ""
                echo -e "${BLUE}═══ LETTA AI CONFIG ═══${NC}"
                echo ""
                echo -e "${CYAN}Current Config:${NC}"
                [[ -f "$HOME/.letta_api_key" ]] && echo "  API Key: ****$(tail -c 8 $HOME/.letta_api_key 2>/dev/null)" || echo "  API Key: Not set"
                [[ -f "$HOME/.letta_agent_id" ]] && echo "  Agent ID: $(cat $HOME/.letta_agent_id 2>/dev/null)" || echo "  Agent ID: Not set"
                echo ""
                echo "1) Set/Update API Key"
                echo "2) Set Agent ID"
                echo "3) List My Agents"
                echo "4) Create New Agent"
                echo "0) Back"
                echo ""
                read -p "Pilih: " letta_op
                case $letta_op in
                    1)
                        echo ""
                        echo "Get key: https://app.letta.com/settings/keys"
                        read -p "Enter Letta API Key: " new_key
                        if [[ -n "$new_key" ]]; then
                            echo "$new_key" > "$HOME/.letta_api_key"
                            chmod 600 "$HOME/.letta_api_key"
                            echo -e "${GREEN}✓ API Key saved!${NC}"
                        fi
                        ;;
                    2)
                        echo ""
                        read -p "Enter Agent ID: " agent_id
                        if [[ -n "$agent_id" ]]; then
                            echo "$agent_id" > "$HOME/.letta_agent_id"
                            echo -e "${GREEN}✓ Agent ID saved!${NC}"
                        fi
                        ;;
                    3)
                        echo ""
                        echo "Fetching agents..."
                        if [[ -f "$HOME/.letta_api_key" ]]; then
                            key=$(cat "$HOME/.letta_api_key")
                            curl -s "https://api.letta.com/v1/agents" \
                                -H "Authorization: Bearer $key" | \
                                python3 -c "import sys,json; d=json.load(sys.stdin); [print(f'  {i+1}) {a.get(\"name\",\"?\")} - {a.get(\"id\",\"?\")}') for i,a in enumerate(d)]" 2>/dev/null || echo "  No agents or error"
                        else
                            echo -e "${RED}No API key set${NC}"
                        fi
                        ;;
                    4)
                        echo ""
                        if [[ -f "$HOME/.letta_api_key" ]]; then
                            key=$(cat "$HOME/.letta_api_key")
                            read -p "Agent name: " aname
                            [[ -z "$aname" ]] && aname="claude-agent"
                            echo "Creating agent '$aname'..."
                            resp=$(curl -s -X POST "https://api.letta.com/v1/agents" \
                                -H "Authorization: Bearer $key" \
                                -H "Content-Type: application/json" \
                                -d "{\"name\":\"$aname\",\"model\":\"anthropic/claude-sonnet-4-20250514\",\"embedding\":\"openai/text-embedding-3-small\"}")
                            agent_id=$(echo "$resp" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)
                            if [[ -n "$agent_id" ]]; then
                                echo "$agent_id" > "$HOME/.letta_agent_id"
                                echo -e "${GREEN}✓ Agent created: $agent_id${NC}"
                            else
                                echo -e "${RED}✗ Failed to create agent${NC}"
                            fi
                        else
                            echo -e "${RED}No API key set${NC}"
                        fi
                        ;;
                esac
                ;;
            4)
                # MiniMax Manager
                echo ""
                echo -e "${BLUE}═══ MINIMAX CONFIG ═══${NC}"
                echo ""
                echo -e "${CYAN}Current Config:${NC}"
                [[ -f "$HOME/.minimax_api_key" ]] && echo "  API Key: ****$(tail -c 8 $HOME/.minimax_api_key 2>/dev/null)" || echo "  API Key: Not set"
                echo ""
                echo "1) Set/Update API Key"
                echo "2) Test Text-to-Audio"
                echo "3) Test Music Generation"
                echo "4) List Available Voices"
                echo "0) Back"
                echo ""
                read -p "Pilih: " mm_op
                case $mm_op in
                    1)
                        echo ""
                        echo "Get key: https://platform.minimax.io/user-center/basic-information/interface-key"
                        read -p "Enter MiniMax API Key: " new_key
                        if [[ -n "$new_key" ]]; then
                            echo "$new_key" > "$HOME/.minimax_api_key"
                            chmod 600 "$HOME/.minimax_api_key"
                            echo -e "${GREEN}✓ API Key saved!${NC}"
                        fi
                        ;;
                    2)
                        echo ""
                        echo "Testing Text-to-Audio..."
                        if [[ -f "$HOME/.minimax_api_key" ]]; then
                            key=$(cat "$HOME/.minimax_api_key")
                            resp=$(curl -s "https://api.minimax.io/v1/t2a_v2" \
                                -H "Authorization: Bearer $key" \
                                -H "Content-Type: application/json" \
                                -d '{"model":"speech-2.6-hd","text":"Hello test","voice_setting":{"voice_id":"female-shaonv"}}')
                            if echo "$resp" | grep -q "audio_file\|base_resp"; then
                                echo -e "${GREEN}✓ Text-to-Audio OK!${NC}"
                            else
                                echo -e "${RED}✗ Error: $(echo "$resp" | head -c 100)${NC}"
                            fi
                        else
                            echo -e "${RED}No API key set${NC}"
                        fi
                        ;;
                    3)
                        echo ""
                        echo "Testing Music Generation (takes 30-60s)..."
                        if [[ -f "$HOME/.minimax_api_key" ]]; then
                            key=$(cat "$HOME/.minimax_api_key")
                            resp=$(curl -s "https://api.minimax.io/v1/music_generation" \
                                -H "Authorization: Bearer $key" \
                                -H "Content-Type: application/json" \
                                -d '{"model":"music-01","prompt":"test music","lyrics":"[Verse]\nTest lyrics","refer_voice":"male-qn-qingse"}' \
                                --max-time 90)
                            if echo "$resp" | grep -q "audio_file\|task_id"; then
                                echo -e "${GREEN}✓ Music Generation OK!${NC}"
                            else
                                echo -e "${RED}✗ Error: $(echo "$resp" | head -c 100)${NC}"
                            fi
                        else
                            echo -e "${RED}No API key set${NC}"
                        fi
                        ;;
                    4)
                        echo ""
                        echo -e "${CYAN}Popular MiniMax Voices:${NC}"
                        echo "  • female-shaonv (Female - Young)"
                        echo "  • male-qn-qingse (Male - Clear)"
                        echo "  • audiobook_female_1 (Audiobook Female)"
                        echo "  • cute_boy (Cute Boy)"
                        echo "  • Charming_Lady (Charming Lady)"
                        echo ""
                        echo "Full list: claude-all → MiniMax MCP → list_voices"
                        ;;
                esac
                ;;
            5)
                # Add Custom Model - Pick provider first
                echo ""
                echo -e "${BLUE}═══ ADD MODEL ═══${NC}"
                echo ""
                echo "Pilih provider untuk tambah model:"
                echo ""
                echo "1) 🇨🇳 ZhipuAI/GLM"
                echo "2) 🎵 MiniMax"
                echo "3) 🤖 Claude/Anthropic"
                echo "4) 🧠 Letta AI"
                echo "0) Back"
                echo ""
                read -p "Pilih provider: " prov_choice
                case $prov_choice in
                    1)
                        # Add to GLM
                        GLM_CFG="$SCRIPT_DIR/models/glm/config.json"
                        echo ""
                        echo -e "${CYAN}Add New GLM Model${NC}"
                        read -p "Model ID (e.g., glm-5): " new_id
                        read -p "Model Name (e.g., GLM-5): " new_name
                        read -p "Description: " new_desc
                        if [[ -n "$new_id" && -n "$new_name" ]] && command -v jq &>/dev/null; then
                            jq ".models += [{\"id\":\"$new_id\",\"name\":\"$new_name\",\"description\":\"$new_desc\"}]" "$GLM_CFG" > "${GLM_CFG}.tmp" && mv "${GLM_CFG}.tmp" "$GLM_CFG"
                            echo -e "${GREEN}✓ Model '$new_name' added to GLM!${NC}"
                        fi
                        ;;
                    2)
                        # Add to MiniMax
                        MM_CFG="$SCRIPT_DIR/models/minimax/config.json"
                        echo ""
                        echo -e "${CYAN}Add New MiniMax Model${NC}"
                        read -p "Model ID (e.g., speech-3.0): " new_id
                        read -p "Model Name: " new_name
                        read -p "Description: " new_desc
                        if [[ -n "$new_id" && -n "$new_name" ]] && command -v jq &>/dev/null; then
                            jq ".models += [{\"id\":\"$new_id\",\"name\":\"$new_name\",\"description\":\"$new_desc\"}]" "$MM_CFG" > "${MM_CFG}.tmp" && mv "${MM_CFG}.tmp" "$MM_CFG"
                            echo -e "${GREEN}✓ Model '$new_name' added to MiniMax!${NC}"
                        fi
                        ;;
                    3)
                        # Add to Claude
                        CLAUDE_CFG="$SCRIPT_DIR/models/anthropic/config.json"
                        if [[ ! -f "$CLAUDE_CFG" ]]; then
                            mkdir -p "$(dirname "$CLAUDE_CFG")"
                            echo '{"name":"Anthropic","models":[]}' > "$CLAUDE_CFG"
                        fi
                        echo ""
                        echo -e "${CYAN}Add New Claude Model${NC}"
                        read -p "Model ID (e.g., claude-4-opus): " new_id
                        read -p "Model Name: " new_name
                        read -p "Description: " new_desc
                        if [[ -n "$new_id" && -n "$new_name" ]] && command -v jq &>/dev/null; then
                            jq ".models += [{\"id\":\"$new_id\",\"name\":\"$new_name\",\"description\":\"$new_desc\"}]" "$CLAUDE_CFG" > "${CLAUDE_CFG}.tmp" && mv "${CLAUDE_CFG}.tmp" "$CLAUDE_CFG"
                            echo -e "${GREEN}✓ Model '$new_name' added to Claude!${NC}"
                        fi
                        ;;
                    4)
                        # Add to Letta
                        LETTA_CFG="$SCRIPT_DIR/models/letta/config.json"
                        echo ""
                        echo -e "${CYAN}Add New Letta Model${NC}"
                        read -p "Model ID: " new_id
                        read -p "Model Name: " new_name
                        read -p "Description: " new_desc
                        if [[ -n "$new_id" && -n "$new_name" ]] && command -v jq &>/dev/null; then
                            jq ".models += [{\"id\":\"$new_id\",\"name\":\"$new_name\",\"description\":\"$new_desc\"}]" "$LETTA_CFG" > "${LETTA_CFG}.tmp" && mv "${LETTA_CFG}.tmp" "$LETTA_CFG"
                            echo -e "${GREEN}✓ Model '$new_name' added to Letta!${NC}"
                        fi
                        ;;
                esac
                ;;
            6)
                # Edit Existing Model - Pick provider first
                echo ""
                echo -e "${BLUE}═══ EDIT MODEL ═══${NC}"
                echo ""
                echo "Pilih provider:"
                echo ""
                echo "1) 🇨🇳 ZhipuAI/GLM"
                echo "2) 🎵 MiniMax"
                echo "3) 🤖 Claude/Anthropic"
                echo "4) 🧠 Letta AI"
                echo "0) Back"
                echo ""
                read -p "Pilih provider: " prov_choice

                case $prov_choice in
                    1) CFG_FILE="$SCRIPT_DIR/models/glm/config.json" ;;
                    2) CFG_FILE="$SCRIPT_DIR/models/minimax/config.json" ;;
                    3) CFG_FILE="$SCRIPT_DIR/models/anthropic/config.json" ;;
                    4) CFG_FILE="$SCRIPT_DIR/models/letta/config.json" ;;
                    *) CFG_FILE="" ;;
                esac

                if [[ -n "$CFG_FILE" && -f "$CFG_FILE" ]] && command -v jq &>/dev/null; then
                    echo ""
                    echo -e "${CYAN}Models in config:${NC}"
                    jq -r '.models[] | "\(.id) - \(.name)"' "$CFG_FILE" 2>/dev/null | nl -w2 -s") "
                    echo ""
                    read -p "Model number to edit: " edit_num
                    idx=$((edit_num-1))
                    current_id=$(jq -r ".models[$idx].id // empty" "$CFG_FILE")
                    current_name=$(jq -r ".models[$idx].name // empty" "$CFG_FILE")
                    current_desc=$(jq -r ".models[$idx].description // empty" "$CFG_FILE")
                    if [[ -n "$current_id" ]]; then
                        echo ""
                        echo "Current: $current_id - $current_name"
                        echo "  Desc: $current_desc"
                        echo ""
                        read -p "New ID [$current_id]: " new_id
                        read -p "New Name [$current_name]: " new_name
                        read -p "New Description [$current_desc]: " new_desc
                        new_id=${new_id:-$current_id}
                        new_name=${new_name:-$current_name}
                        new_desc=${new_desc:-$current_desc}
                        jq ".models[$idx] = {\"id\":\"$new_id\",\"name\":\"$new_name\",\"description\":\"$new_desc\"}" "$CFG_FILE" > "${CFG_FILE}.tmp" && mv "${CFG_FILE}.tmp" "$CFG_FILE"
                        echo -e "${GREEN}✓ Model updated!${NC}"
                    else
                        echo -e "${RED}Model not found${NC}"
                    fi
                elif [[ -n "$CFG_FILE" ]]; then
                    echo -e "${RED}Config file not found or jq not installed${NC}"
                fi
                ;;
            7)
                # List All Models from all providers
                echo ""
                echo -e "${BLUE}═══ ALL MODELS ═══${NC}"
                echo ""

                # GLM Models
                GLM_CFG="$SCRIPT_DIR/models/glm/config.json"
                if [[ -f "$GLM_CFG" ]] && command -v jq &>/dev/null; then
                    echo -e "${CYAN}🇨🇳 ZhipuAI/GLM:${NC}"
                    jq -r '.models[] | "  • \(.id) - \(.description)"' "$GLM_CFG" 2>/dev/null
                    echo ""
                fi

                # MiniMax Models
                MM_CFG="$SCRIPT_DIR/models/minimax/config.json"
                if [[ -f "$MM_CFG" ]] && command -v jq &>/dev/null; then
                    echo -e "${CYAN}🎵 MiniMax:${NC}"
                    jq -r '.models[]? | "  • \(.id) - \(.description)"' "$MM_CFG" 2>/dev/null || echo "  (no models configured)"
                    echo ""
                fi

                # Claude/Anthropic Models
                CLAUDE_CFG="$SCRIPT_DIR/models/anthropic/config.json"
                echo -e "${CYAN}🤖 Claude/Anthropic:${NC}"
                if [[ -f "$CLAUDE_CFG" ]] && command -v jq &>/dev/null; then
                    jq -r '.models[]? | "  • \(.id) - \(.description)"' "$CLAUDE_CFG" 2>/dev/null
                fi
                echo "  • claude-sonnet-4-20250514 (Latest Sonnet)"
                echo "  • claude-3-5-sonnet-20241022 (Sonnet 3.5)"
                echo "  • claude-3-5-haiku-20241022 (Haiku - Fast)"
                echo "  • claude-3-opus-20240229 (Opus - Best)"
                echo ""

                # Letta Models
                LETTA_CFG="$SCRIPT_DIR/models/letta/config.json"
                if [[ -f "$LETTA_CFG" ]] && command -v jq &>/dev/null; then
                    echo -e "${CYAN}🧠 Letta AI:${NC}"
                    jq -r '.models[]? | "  • \(.id) - \(.description)"' "$LETTA_CFG" 2>/dev/null || echo "  (uses Claude/GPT via Letta API)"
                    echo ""
                fi
                ;;
            8)
                # API Key Manager
                echo ""
                echo -e "${BLUE}═══ API KEY MANAGER ═══${NC}"
                echo ""
                echo -e "${CYAN}Stored API Keys:${NC}"
                [[ -f "$HOME/.anthropic_api_key" ]] && echo "  ✓ Claude/Anthropic" || echo "  ✗ Claude/Anthropic"
                [[ -f "$HOME/.glm_api_key" ]] && echo "  ✓ ZhipuAI/GLM" || echo "  ✗ ZhipuAI/GLM"
                [[ -f "$HOME/.letta_api_key" ]] && echo "  ✓ Letta AI" || echo "  ✗ Letta AI"
                [[ -f "$HOME/.minimax_api_key" ]] && echo "  ✓ MiniMax" || echo "  ✗ MiniMax"
                [[ -f "$HOME/.openai_api_key" ]] && echo "  ✓ OpenAI"
                [[ -f "$HOME/.groq_api_key" ]] && echo "  ✓ Groq"
                [[ -f "$HOME/.deepseek_api_key" ]] && echo "  ✓ DeepSeek"
                echo ""
                echo "1) Delete Claude API Key"
                echo "2) Delete GLM API Key"
                echo "3) Delete Letta API Key"
                echo "4) Delete MiniMax API Key"
                echo "5) Delete ALL API Keys"
                echo "0) Back"
                echo ""
                read -p "Pilih: " key_op
                case $key_op in
                    1) rm -f "$HOME/.anthropic_api_key" && echo -e "${GREEN}✓ Deleted${NC}" ;;
                    2) rm -f "$HOME/.glm_api_key" && echo -e "${GREEN}✓ Deleted${NC}" ;;
                    3) rm -f "$HOME/.letta_api_key" "$HOME/.letta_agent_id" && echo -e "${GREEN}✓ Deleted${NC}" ;;
                    4) rm -f "$HOME/.minimax_api_key" && echo -e "${GREEN}✓ Deleted${NC}" ;;
                    5)
                        read -p "Are you sure? (yes/no): " confirm
                        if [[ "$confirm" == "yes" ]]; then
                            rm -f "$HOME"/.*_api_key "$HOME/.letta_agent_id"
                            echo -e "${GREEN}✓ All API keys deleted${NC}"
                        fi
                        ;;
                esac
                ;;
            9)
                # View All Configs
                echo ""
                echo -e "${BLUE}═══ ALL CONFIGURATIONS ═══${NC}"
                echo ""
                echo -e "${CYAN}🤖 Claude/Anthropic:${NC}"
                [[ -f "$HOME/.anthropic_api_key" ]] && echo "  ✓ API Key: ****$(tail -c 8 $HOME/.anthropic_api_key)" || echo "  ✗ API Key not set"
                echo ""
                echo -e "${CYAN}🇨🇳 ZhipuAI/GLM:${NC}"
                [[ -f "$HOME/.glm_api_key" ]] && echo "  ✓ API Key: ****$(tail -c 8 $HOME/.glm_api_key)" || echo "  ✗ API Key not set"
                echo ""
                echo -e "${CYAN}🧠 Letta AI:${NC}"
                [[ -f "$HOME/.letta_api_key" ]] && echo "  ✓ API Key: ****$(tail -c 8 $HOME/.letta_api_key)" || echo "  ✗ API Key not set"
                [[ -f "$HOME/.letta_agent_id" ]] && echo "  ✓ Agent ID: $(cat $HOME/.letta_agent_id)" || echo "  ✗ Agent ID not set"
                echo ""
                echo -e "${CYAN}🎵 MiniMax:${NC}"
                [[ -f "$HOME/.minimax_api_key" ]] && echo "  ✓ API Key: ****$(tail -c 8 $HOME/.minimax_api_key)" || echo "  ✗ API Key not set"
                echo ""
                echo -e "${CYAN}📁 Other Keys:${NC}"
                for kf in "$HOME"/.{openai,groq,perplexity,cohere,deepseek,mistral,moonshot,openrouter}_api_key; do
                    [[ -f "$kf" ]] && echo "  ✓ $(basename $kf _api_key | sed 's/^\.//')"
                done
                ;;
            10)
                # Reset Config
                echo ""
                echo -e "${RED}⚠️  This will delete all configurations!${NC}"
                read -p "Type 'RESET' to confirm: " confirm
                if [[ "$confirm" == "RESET" ]]; then
                    rm -f "$HOME"/.*_api_key "$HOME/.letta_agent_id" "$HOME/.claude.json"
                    echo -e "${GREEN}✓ All configs reset${NC}"
                fi
                ;;
            0|*)
                exec "$0"
                ;;
        esac
        echo ""
        echo -e "${YELLOW}Press Enter untuk kembali...${NC}"
        read
        exec "$0"
        ;;
    21)
        # Letta AI - Stateful AI Agents
        echo -e "${BLUE}Configuring for Letta AI...${NC}"
        echo -e "${YELLOW}Note: Letta requires agent creation before chat. Let's create one first.${NC}"

        # Get API key with persistent storage
        if [[ -z "$LETTA_API_KEY" ]]; then
            load_api_key_to_var "$HOME/.letta_api_key" "LETTA_API_KEY"
        fi

        if [[ -z "$LETTA_API_KEY" ]]; then
            echo "Get Key: https://docs.letta.com"
            read -p "Enter Letta API Key: " LETTA_API_KEY
            save_api_key "$LETTA_API_KEY" "$HOME/.letta_api_key" "Letta"
        else
            if [[ ! -f "$HOME/.letta_api_key" ]]; then
                save_api_key "$LETTA_API_KEY" "$HOME/.letta_api_key" "Letta"
            fi
        fi
        export LETTA_API_KEY

        # Check if agent exists or create new one
        echo -e "${BLUE}Letta Agent Management:${NC}"
        echo "1) List existing agents"
        echo "2) Create new agent"
        echo "3) Use existing agent ID"
        echo ""
        read -p "Choose option [1-3]: " letta_option

        case $letta_option in
            1)
                echo -e "${BLUE}Listing agents...${NC}"
                curl -s -X GET "https://api.letta.com/v1/agents" \
                     -H "Authorization: Bearer $LETTA_API_KEY" | \
                    python3 -c "import sys,json; data=json.load(sys.stdin); [print(f'{i+1}) {a[\"name\"]} - {a[\"id\"]}') for i,a in enumerate(data.get('agents',[]))]" 2>/dev/null || \
                    echo "No agents found or API error"
                echo ""
                read -p "Enter agent ID (or press Enter to create new): " agent_id
                [[ -z "$agent_id" ]] && letta_option=2
                ;;
            2)
                echo -e "${BLUE}Creating new Letta agent...${NC}"
                read -p "Agent name [default: claude-agent]: " agent_name
                [[ -z "$agent_name" ]] && agent_name="claude-agent"

                read -p "Model [default: openai/gpt-4o-mini]: " letta_model
                [[ -z "$letta_model" ]] && letta_model="openai/gpt-4o-mini"

                read -p "Embedding [default: openai/text-embedding-3-small]: " embedding
                [[ -z "$embedding" ]] && embedding="openai/text-embedding-3-small"

                echo "Creating agent..."
                response=$(curl -s -X POST "https://api.letta.com/v1/agents" \
                     -H "Authorization: Bearer $LETTA_API_KEY" \
                     -H "Content-Type: application/json" \
                     -d "{
                       \"name\": \"$agent_name\",
                       \"model\": \"$letta_model\",
                       \"embedding\": \"$embedding\",
                       \"memory_blocks\": [
                         {\"label\": \"human\", \"value\": \"User interacting via Claude-All launcher\"},
                         {\"label\": \"persona\", \"value\": \"I am a helpful AI assistant with long-term memory\"}
                       ]
                     }")

                if echo "$response" | python3 -c "import sys,json; json.load(sys.stdin)" 2>/dev/null; then
                    agent_id=$(echo "$response" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id', ''))" 2>/dev/null)
                    echo -e "${GREEN}✓ Agent created successfully!${NC}"
                    echo -e "${GREEN}Agent ID: $agent_id${NC}"
                else
                    echo -e "${RED}❌ Failed to create agent${NC}"
                    echo "Response: $response"
                    exit 1
                fi
                ;;
            3)
                read -p "Enter existing agent ID: " agent_id
                ;;
        esac

        if [[ -n "$agent_id" ]]; then
            echo -e "${GREEN}✓ Using Letta agent: $agent_id${NC}"
            echo -e "${YELLOW}Note: You're now using Letta's agent system. Messages are sent to Letta API.${NC}"
            echo -e "${BLUE}🚀 Starting Letta agent chat...${NC}"
            echo -e "${CYAN}Agent will maintain memory and context across conversations.${NC}"

            # Create a simple chat interface with Letta
            while true; do
                echo ""
                read -p "You: " user_message
                [[ "$user_message" == "exit" ]] && break

                echo -e "${BLUE}Agent:${NC}"
                curl -s -X POST "https://api.letta.com/v1/agents/$agent_id/messages" \
                     -H "Authorization: Bearer $LETTA_API_KEY" \
                     -H "Content-Type: application/json" \
                     -d "{\"messages\": [{\"role\": \"user\", \"content\": \"$user_message\"}]}" | \
                    python3 -c "
import sys,json
try:
    data=json.load(sys.stdin)
    if 'messages' in data and data['messages']:
        for msg in data['messages']:
            if msg.get('role') == 'assistant':
                print(msg.get('content', ''))
    else:
        print('No response received')
        print('Debug:', data)
except:
    print('Error parsing response')
"
            done
        else
            echo -e "${RED}No agent ID provided. Exiting...${NC}"
        fi
        ;;
    22)
        # Custom API Endpoint
        check_dependencies
        echo -e "${BLUE}Configuring Custom API Endpoint...${NC}"
        read -p "Enter API Base URL (e.g. https://api.example.com/v1): " CUSTOM_BASE
        read -p "Enter API Key: " CUSTOM_KEY
        read -p "Enter Model Name: " MODEL_NAME

        export ANTHROPIC_BASE_URL="$CUSTOM_BASE"
        export ANTHROPIC_API_KEY="$CUSTOM_KEY"
        echo -e "${BLUE}🚀 Starting with custom endpoint...${NC}"
        exec claude --no-chrome --model "$MODEL_NAME" "$@"
        ;;
esac

# Handle custom models (22+) but exclude model manager
if [[ "$choice" =~ ^[0-9]+$ ]] && [[ $choice -ge 22 ]] && [[ -n "$model_manager_num" ]] && [[ $choice -lt $model_manager_num ]]; then
    custom_index=$((choice - 22))
    count=0
    while IFS= read -r model_info; do
        if [[ -n "$model_info" ]]; then
            if [[ $count -eq $custom_index ]]; then
                IFS=':' read -r filename provider_name description <<< "$model_info"
                echo -e "${BLUE}Using ${provider_name}...${NC}"
                handle_custom_model "$filename" "$@"
                exit 0
            fi
            ((count++))
        fi
    done < <(get_custom_models)
fi

# Handle model manager - check dynamic number
if [[ "$choice" -eq "$model_manager_num" ]]; then
    if [[ -f "$SCRIPT_DIR/scripts/add-model-manual.sh" ]]; then
        exec "$SCRIPT_DIR/scripts/add-model-manual.sh"
    else
        echo -e "${RED}Error: add-model-manual.sh not found in scripts/${NC}"
        exit 1
    fi
fi

echo "Invalid choice"
exit 1
