#!/bin/bash

# The extensions to be harvested with or without version 
EXTENSIONS=(
    "james-yu.latex-workshop"
    "redhat.java@1.25.0"
    "ms-python.python"
)

TARGET_DIR="./vscode_harvest"
mkdir -p "$TARGET_DIR"

echo "--- Starte Profi-Harvesting (API-Link Extraction) ---"

for entry in "${EXTENSIONS[@]}"; do

# extension names may contain a version 
    if [[ $entry == *"@"* ]]; then
      # Here, we have a concrete version 
        FULL_ID=$(echo $entry | cut -d'@' -f1)
        VER=$(echo $entry | cut -d'@' -f2)
    else
        #
        FULL_ID=$entry
        VER="latest"
    fi

    PUBLISHER=$(echo $FULL_ID | cut -d. -f1)
    EXT_NAME=$(echo $FULL_ID | cut -d. -f2)

    echo -n "Suche $FULL_ID ($VER)... "

    # 2. Frage die API nach dem echten Download-URL aus dem JSON
    # Wir fischen den Wert aus 'files.download.url'
    API_URL="https://open-vsx.org/api/$PUBLISHER/$EXT_NAME/$VER"
    REAL_DOWNLOAD_URL=$(curl -s "$API_URL" | jq -r '.files.download.url')

    # 3. Sicherheitscheck: Haben wir einen validen Link bekommen?
    if [[ "$REAL_DOWNLOAD_URL" == "null" ]] || [[ -z "$REAL_DOWNLOAD_URL" ]]; then
        echo "❌ Nicht gefunden (API Fehler)"
        continue
    fi

    # 4. Download mit dem exakten Link vom Server
    OUT_FILE="$TARGET_DIR/$FULL_ID.vsix"
    echo -n "Lade... "
    
    if curl -L -s -o "$OUT_FILE" "$REAL_DOWNLOAD_URL"; then
        echo "✅ (Größe: $(du -h "$OUT_FILE" | cut -f1))"
    else
        echo "❌ Download-Fehler"
    fi
done

echo "--- Fertig! Alle Files liegen in $TARGET_DIR ---"