#!/bin/bash
# Script to update shared settings across all bot configs

set -e

CONFIG_DIRS=(
    ~/.nanobot-user1
    ~/.nanobot-user2
    ~/.nanobot-user3
)

# Function to update a specific key in all configs
update_config_key() {
    local key_path="$1"
    local new_value="$2"
    
    echo "Updating $key_path to $new_value in all configs..."
    
    for dir in "${CONFIG_DIRS[@]}"; do
        config_file="$dir/config.json"
        if [ -f "$config_file" ]; then
            # Use jq to update the config
            if command -v jq &> /dev/null; then
                # Convert key_path like "providers.openrouter.apiKey" to jq path
                jq_path=$(echo "$key_path" | sed 's/\./"."/g' | sed 's/^/./' | sed 's/\.$//')
                jq "$jq_path = \"$new_value\"" "$config_file" > "$config_file.tmp" && mv "$config_file.tmp" "$config_file"
                echo "  ✓ Updated $config_file"
            else
                echo "  ⚠ jq not found, skipping $config_file (install jq for automatic updates)"
            fi
        else
            echo "  ⚠ Config not found: $config_file"
        fi
    done
}

# Function to show usage
usage() {
    cat << EOF
Usage: $0 <command> [args]

Commands:
  update-api-key <provider> <key>     Update API key for a provider (e.g., openrouter)
  update-model <model>                 Update default model
  update-setting <key.path> <value>    Update any setting using dot notation
  
Examples:
  $0 update-api-key openrouter "sk-or-v1-xxx"
  $0 update-model "anthropic/claude-opus-4-5"
  $0 update-setting "agents.defaults.temperature" "0.8"
  
Note: Requires 'jq' to be installed for automatic updates.
      Install with: sudo apt install jq  (or brew install jq on macOS)
EOF
}

# Main script
if [ $# -eq 0 ]; then
    usage
    exit 1
fi

case "$1" in
    update-api-key)
        if [ $# -ne 3 ]; then
            echo "Error: update-api-key requires provider name and API key"
            usage
            exit 1
        fi
        provider="$2"
        api_key="$3"
        update_config_key "providers.$provider.apiKey" "$api_key"
        ;;
    update-model)
        if [ $# -ne 2 ]; then
            echo "Error: update-model requires model name"
            usage
            exit 1
        fi
        model="$2"
        update_config_key "agents.defaults.model" "$model"
        ;;
    update-setting)
        if [ $# -ne 3 ]; then
            echo "Error: update-setting requires key path and value"
            usage
            exit 1
        fi
        key_path="$2"
        value="$3"
        update_config_key "$key_path" "$value"
        ;;
    *)
        echo "Unknown command: $1"
        usage
        exit 1
        ;;
esac

echo ""
echo "Done! Restart containers to apply changes:"
echo "  docker compose -f docker-compose.multi.yml restart"


