#!/bin/bash

select_fastest_url() {
  local urls=("$@")
  local best_url=""
  local best_speed=0

  local url_backup="$2"

  if [ ${#urls[@]} -eq 0 ]; then
    echo "❌ Please provide at least one URL"
    exit 1
  fi

  for url in "${urls[@]}"; do
    local speed=$(curl -o /dev/null -s -w "%{speed_download}" --max-time 5 "$url")

    if [[ -z "$speed" || "$speed" == "0.000" ]]; then
      continue
    fi

    local speed_kbps=$(echo "$speed / 1024" | bc -l)

    if (( $(echo "$speed > $best_speed" | bc -l) )); then
      best_speed=$speed
      best_url=$url
    fi
  done

  echo ""
  if [ -n "$best_url" ]; then
    local best_kbps=$(echo "$best_speed / 1024" | bc -l)
    echo "${best_url}"
    return 0
  else
    echo "${url_backup}"
  fi
}


echo "configuring..."
MAX_RETRIES=3
download_file() {
    local url="$1"
    local output="$2"
    local attempt=1
    local error_msg=""

    echo "Starting download: $url -> $output"

    while [ $attempt -le $MAX_RETRIES ]; do
        echo "Attempt $attempt of $MAX_RETRIES..."
        curl -fSL "$url" -o "$output"
        if [ $? -eq 0 ]; then
            echo "✅ Download succeeded: $output"
            return 0
        else
            echo "❌ Download failed"
            ((attempt++))
            sleep 1
        fi
    done

    echo "🚨 Error: Download failed after $MAX_RETRIES attempts. Exiting."
    echo "Last error message: $error_msg"
    exit 1
}



# Function to detect OS and set package manager
if [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    PKG_MANAGER="brew"
    UPDATE_CMD="brew update"
    INSTALL_CMD="brew install"
    SETTINGS_PATH="$HOME/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json"
    NPM_INSTALL_FLAGS=""


    SETTINGS_PATH="$HOME/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json"
    echo "installing nodejs..."
    if uname -a | grep -qi arm; then
  			NODE_FILENAME="node-v22.14.0-darwin-arm64"
    else
    		NODE_FILENAME="node-v22.14.0-darwin-x64"
    fi

    tsinghua_url="https://mirrors.tuna.tsinghua.edu.cn/nodejs-release/v22.14.0/${NODE_FILENAME}.tar.gz"
    official_url="https://nodejs.org/dist/v22.14.0/${NODE_FILENAME}.tar.gz"
    echo "selecting the fastest mirror..."
    fastest_url=$(select_fastest_url "${tsinghua_url}" "${official_url}")
    echo "✅ using ${fastest_url}"
    download_file ${fastest_url} ${NODE_FILENAME}.tar.gz

    tar -xzf ${NODE_FILENAME}.tar.gz
    NODE_PATH="$(pwd)/${NODE_FILENAME}/bin"
    echo "export PATH=\"$NODE_PATH:\$PATH\"" >> ~/.bash_profile
    echo "export PATH=\"$NODE_PATH:\$PATH\"" >> ~/.zshrc
    source ~/.bash_profile
    echo "✅ nodejs installed!"
    
elif [ -f /etc/os-release ]; then
    . /etc/os-release
    if [[ "$ID" == "ubuntu" || "$ID" == "debian" ]]; then
        PKG_MANAGER="apt"
        UPDATE_CMD="apt update"
        INSTALL_CMD="apt install -y"
    elif [[ "$ID" == "centos" || "$ID" == "rhel" || "$ID" == "anolis" ]]; then
        PKG_MANAGER="yum"
        UPDATE_CMD="yum update -y"
        INSTALL_CMD="yum install -y"
    elif [[ "$ID" == "fedora" ]]; then
        PKG_MANAGER="dnf"
        UPDATE_CMD="dnf update -y"
        INSTALL_CMD="dnf install -y"
    else
        echo "Unsupported Linux distribution: $ID"
        exit 1
    fi
    SETTINGS_PATH="$HOME/.config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json"
    
    echo "installing nodejs..."
    tsinghua_url="https://mirrors.tuna.tsinghua.edu.cn/nodejs-release/v22.14.0/node-v22.14.0-linux-x64.tar.gz"
    official_url="https://nodejs.org/dist/v22.14.0/node-v22.14.0-linux-x64.tar.gz"
    echo "selecting the fastest mirror..."
    fastest_url=$(select_fastest_url "${tsinghua_url}" "${official_url}")
    echo "✅ using ${fastest_url}"
    download_file ${fastest_url} node-v22.14.0-linux-x64.tar.gz

    tar -xzf node-v22.14.0-linux-x64.tar.gz
    NODE_PATH="$(pwd)/node-v22.14.0-linux-x64/bin"
    echo "export PATH=\"$NODE_PATH:\$PATH\"" >> ~/.bashrc
    source ~/.bashrc
    echo "✅ nodejs installed!"
    
else
    echo "Unsupported operating system"
    exit 1
fi

export PATH=$NODE_PATH:$PATH
targets=("smartcogent" "smartcogent.zip" "mcptool")

found=0
for target in "${targets[@]}"; do
    if [ -e "$target" ]; then
        found=1
        break
    fi
done

if [ $found -eq 1 ]; then
    echo "Exising installation found:"
    for target in "${targets[@]}"; do
        if [ -e "$target" ]; then
            echo " - $target"
        fi
    done

    read -p "Would you like to remove the existing installation? (Y/N): " answer </dev/tty
    case $answer in
        [Yy]* )
            echo "Removing the existing installation..."
            for target in "${targets[@]}"; do
                if [ -e "$target" ]; then
                    rm -rf "$target"
                fi
            done
            ;;
        * )
            echo "Installation has been canceled. Exiting..."
            exit 1
            ;;
    esac
fi

# Check and install unzip
if ! command -v unzip >/dev/null 2>&1; then
    echo "unzip is not installed, installing unzip..."
    if [[ "$PKG_MANAGER" == "brew" ]]; then
        $UPDATE_CMD && $INSTALL_CMD unzip
    else
        $UPDATE_CMD && $INSTALL_CMD unzip
    fi
    if [ $? -eq 0 ]; then
        echo "✅ Successfully installed unzip"
    else
        echo "Failed to install unzip"
        exit 1
    fi
else
    echo "unzip is installed at $(command -v unzip)"
fi

echo "downloading smartcogent..."
download_file https://static.zan.top/smartcogent/smartcogent-1.0.0.tgz smartcogent-1.0.0.tgz
if [ $? -eq 0 ]; then
    echo "✅ Successfully download SmartCogent"
else
    echo "Failed to download SmartCogent"
    exit 1
fi

echo "installing smartcogent..."
${NODE_PATH}/npm install -g smartcogent-1.0.0.tgz
if [ $? -eq 0 ]; then
    echo "✅ npm installed successfully"
else
    # TODO 
    sudo ${NODE_PATH}/npm install
    if [ $? -eq 0 ]; then
        echo "npm installed successfully"
    else
        echo "npm installation failed"
        exit 1
    fi
fi


# Define JSON content with current directory
json_content=$(cat <<EOF
{
  "mcpServers": {
    "contract-full-client": {
      "autoApprove": [],
      "disabled": false,
      "timeout": 3600,
      "command": "${NODE_PATH}/npx",
      "args": [
        "${NODE_PATH}/smartcogent"
      ],
      "env": {
        "ZAN_ACCESS_KEY": "<your_zan_access_key>",
        "RPC_URL": "<your_chain_rpc_url>",
        "ACCOUNT_ADDRESS": "<your_chain_account>",
        "HOSTING": "metamask"
      },
      "transportType": "stdio"
    }
  }
}
EOF
)

# Output settings file path and JSON content
echo
echo
echo "✅ Cline MCP settings file location: $SETTINGS_PATH"
echo "✅ Add our tool to your Cline MCP settings:"
echo "$json_content"
echo "$json_content" > ./cline_mcp_settings.json
echo "✅ Save the settings to ./cline_mcp_settings.json"