#!/bin/bash
# Download 1Password SDK native libraries for offline builds
#
# This script downloads all 4 platform-specific libraries from PyPI,
# verifies SHA256 checksums, and extracts them to src/libs/.
#
# Usage: ./scripts/download-libs.sh

set -euo pipefail

SDK_VERSION="0.3.2"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
LIBS_DIR="$PROJECT_ROOT/src/libs"

# Platform configurations: platform_tag|lib_name|output_dir
PLATFORMS=(
    "manylinux_2_32_x86_64|libop_uniffi_core.so|linux-x86_64"
    "manylinux_2_32_aarch64|libop_uniffi_core.so|linux-aarch64"
    "macosx_10_9_x86_64|libop_uniffi_core.dylib|macos-x86_64"
    "macosx_11_0_arm64|libop_uniffi_core.dylib|macos-aarch64"
)

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check required tools
check_dependencies() {
    local missing=()

    for cmd in curl jq unzip sha256sum; do
        if ! command -v "$cmd" &> /dev/null; then
            missing+=("$cmd")
        fi
    done

    if [[ ${#missing[@]} -gt 0 ]]; then
        log_error "Missing required tools: ${missing[*]}"
        log_info "Install with: sudo apt-get install curl jq unzip coreutils"
        exit 1
    fi
}

# Fetch wheel info (URL and SHA256) from PyPI
get_wheel_info() {
    local platform_tag="$1"
    local api_url="https://pypi.org/pypi/onepassword-sdk/${SDK_VERSION}/json"

    local response
    response=$(curl -sS "$api_url")

    # Find wheel matching platform tag
    echo "$response" | jq -r --arg tag "$platform_tag" '
        .urls[] |
        select(.filename | contains($tag) and endswith(".whl")) |
        "\(.url)|\(.digests.sha256)"
    ' | head -n1
}

# Download and verify a single library
download_library() {
    local platform_tag="$1"
    local lib_name="$2"
    local output_dir="$3"

    local target_dir="$LIBS_DIR/$output_dir"
    local lib_path="$target_dir/$lib_name"

    log_info "Processing $output_dir..."

    # Get wheel info from PyPI
    local wheel_info
    wheel_info=$(get_wheel_info "$platform_tag")

    if [[ -z "$wheel_info" ]]; then
        log_error "Could not find wheel for platform: $platform_tag"
        return 1
    fi

    local url sha256
    url=$(echo "$wheel_info" | cut -d'|' -f1)
    sha256=$(echo "$wheel_info" | cut -d'|' -f2)

    log_info "  URL: $url"
    log_info "  Expected SHA256: $sha256"

    # Create temp directory for download
    local tmp_dir
    tmp_dir=$(mktemp -d)
    trap "rm -rf $tmp_dir" RETURN

    local wheel_file="$tmp_dir/wheel.whl"

    # Download wheel
    log_info "  Downloading..."
    curl -sS -L -o "$wheel_file" "$url"

    # Verify checksum
    local actual_sha256
    actual_sha256=$(sha256sum "$wheel_file" | cut -d' ' -f1)

    if [[ "$actual_sha256" != "$sha256" ]]; then
        log_error "SHA256 checksum mismatch!"
        log_error "  Expected: $sha256"
        log_error "  Actual:   $actual_sha256"
        return 1
    fi
    log_info "  SHA256 verified"

    # Extract library from wheel (it's a ZIP file)
    log_info "  Extracting..."
    mkdir -p "$target_dir"

    # Find and extract the library file
    local lib_path_in_zip
    lib_path_in_zip=$(unzip -l "$wheel_file" | grep "$lib_name" | awk '{print $4}' | head -n1)

    if [[ -z "$lib_path_in_zip" ]]; then
        log_error "Library $lib_name not found in wheel"
        return 1
    fi

    unzip -p "$wheel_file" "$lib_path_in_zip" > "$lib_path"
    chmod 755 "$lib_path"

    log_info "  Extracted to: $lib_path"
}

main() {
    log_info "1Password SDK Library Downloader"
    log_info "SDK Version: $SDK_VERSION"
    log_info "Output directory: $LIBS_DIR"
    echo ""

    check_dependencies

    # Create libs directory
    mkdir -p "$LIBS_DIR"

    local failed=0

    for platform in "${PLATFORMS[@]}"; do
        IFS='|' read -r platform_tag lib_name output_dir <<< "$platform"

        if ! download_library "$platform_tag" "$lib_name" "$output_dir"; then
            log_error "Failed to download $output_dir"
            ((failed++))
        fi
        echo ""
    done

    if [[ $failed -gt 0 ]]; then
        log_error "$failed platform(s) failed to download"
        exit 1
    fi

    log_info "All libraries downloaded successfully!"
    log_info ""
    log_info "Library sizes:"
    du -sh "$LIBS_DIR"/*/* 2>/dev/null || true
}

main "$@"
