#!/bin/bash

# Usage: ./download_wheels.sh <package_name> <version>
# Example: ./download_wheels.sh Pillow 12.2.0

if [ $# -ne 2 ]; then
    echo "Usage: $0 <package_name> <version>"
    echo "Example: $0 Pillow 12.2.0"
    exit 1
fi

PACKAGE="$1"
VERSION="$2"
OUTPUT_DIR="./unified"
# Python versions
PYTHON_VERSIONS=("3.11" "3.12" "3.13")
# PyPI platforms
PLATFORMS=(
    "manylinux_2_28_x86_64"  # Modern Linux x86_64
    "win_amd64"              # Windows x64
    "macosx_13_0_arm64"      # macOS Apple Silicon (M1/M2/M3...)
)
# Snapshot of files already present before the download
EXISTING_FILES=$(ls -1 "$OUTPUT_DIR" 2>/dev/null)
echo "Starting the wheel download for $PACKAGE==$VERSION..."
echo "Files will be saved in: $OUTPUT_DIR"
echo "------------------------------------------------"
for py in "${PYTHON_VERSIONS[@]}"; do
    for plat in "${PLATFORMS[@]}"; do
        echo "[INFO] Attempting download for Python $py on platform $plat..."
        # The key flag here is --no-deps, essential when doing cross-platform downloads
        pip download \
            --only-binary=:all: \
            --no-deps \
            --dest "$OUTPUT_DIR" \
            --python-version "$py" \
            --platform "$plat" \
            --implementation "cp" \
            "${PACKAGE}==${VERSION}"
        if [ $? -eq 0 ]; then
            echo "[OK] Downloaded successfully!"
        else
            echo "[ERROR] Not found or failed for Python $py ($plat)"
        fi
        echo "------------------------------------------------"
    done
done
echo "Newly downloaded wheels:"
for f in $(ls -1 "$OUTPUT_DIR" 2>/dev/null); do
    if ! echo "$EXISTING_FILES" | grep -qx "$f"; then
        ls -lh "$OUTPUT_DIR/$f"
    fi
done
