#!/usr/bin/env bash
# @author juntao

# --- Configuration ---
SEARCH_DIR="app/build/generated/ksp/"
JSON_FILE_NAME="router-map-of-app.json"
UPLOAD_URL="https://app-api.ghzs6.com/app_router_map"
TOKEN="672b30260e33cf5e1540ff31"
VERSION=$(awk -v FS="versionName = " 'NF>1{print $2}' dependencies.gradle | sed "s/\"//g")
# --- End Configuration ---

# Do the build stuff to create a new JSON file
./gradlew clean
./gradlew assemblePublishCnRelease -PENABLE_ROUTE_DOC=true

# Find the JSON file
JSON_FILE=$(find "$SEARCH_DIR" -type f -path "*/resources/com/gh/gamecenter/route/docs/*" -name "$JSON_FILE_NAME" -print -quit)

# Check if jq is installed
if ! command -v jq &> /dev/null; then
    echo "jq is not installed. Attempting to install..."

    # Try to determine the operating system
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        # Assume Debian/Ubuntu
        if command -v apt-get &> /dev/null; then
            sudo apt-get update
            sudo apt-get install -y jq
        else
            echo "Error: Could not determine package manager for Linux distribution."
            exit 1
        fi
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        # Assume macOS (using Homebrew)
        if command -v brew &> /dev/null; then
            brew update
            brew install jq
        else
            echo "Error: Homebrew is not installed on macOS. Please install it from https://brew.sh/"
            exit 1
        fi
    else
        echo "Error: Unsupported operating system: $OSTYPE"
        exit 1
    fi

    # Verify jq installation
    if ! command -v jq &> /dev/null; then
        echo "Error: jq installation failed."
        exit 1
    fi
fi

# Check if the JSON file exists
if [ ! -f "$JSON_FILE" ]; then
    echo "Error: JSON file not found: $JSON_FILE"
    exit 1
fi

# Use jq to construct the required JSON structure
NEW_JSON=$(jq -n \
    --arg version "$VERSION" \
    --argjson router_map "$(cat "$JSON_FILE")" \
    '{version: $version, router_map: $router_map}')

# Upload the new JSON using curl
curl -X POST \
     -H "Content-Type: application/json" \
     -H "TOKEN: $TOKEN" \
     -d "$NEW_JSON" \
     "$UPLOAD_URL"