#!/usr/bin/env pwsh
# Download script for all-MiniLM-L6-v2 ONNX model
# Run this script to download the embedding model locally

$ModelUrl = "https://huggingface.co/ sentence-transformers/all-MiniLM-L6-v2/resolve/main/onnx/model.onnx"
$OutputPath = "Models/all-MiniLM-L6-v2.onnx"
$BaseUrl = "https://huggingface.co"

# The all-MiniLM-L6-v2 ONNX model is available from HuggingFace
# We'll use the transformers.js format which is pre-quantized and optimized

Write-Host "Downloading all-MiniLM-L6-v2 ONNX model..." -ForegroundColor Cyan
Write-Host "Model URL: $ModelUrl" -ForegroundColor Gray

# Alternative: Download from Xenova/transformers.js releases
$AltUrl = "https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/quantized/all-MiniLM-L6-v2_quantized.onnx"

try {
    Write-Host "Attempting download from jsDelivr CDN..." -ForegroundColor Yellow
    $ProgressPreference = 'SilentlyContinue'
    
    # Download using curl or Invoke-WebRequest
    if (Get-Command curl -ErrorAction SilentlyContinue) {
        curl -L -o $OutputPath $AltUrl
    } else {
        Invoke-WebRequest -Uri $AltUrl -OutFile $OutputPath -UseBasicParsing
    }
    
    if (Test-Path $OutputPath) {
        $size = (Get-Item $OutputPath).Length / 1MB
        Write-Host "Successfully downloaded model to $OutputPath" -ForegroundColor Green
        Write-Host "File size: $([math]::Round($size, 2)) MB" -ForegroundColor Gray
    } else {
        throw "Download failed - file not created"
    }
}
catch {
    Write-Host "Error downloading model: $_" -ForegroundColor Red
    Write-Host "" -ForegroundColor White
    Write-Host "Manual download instructions:" -ForegroundColor White
    Write-Host "1. Visit: https://huggingface.co/Xenova/all-MiniLM-L6-v2" -ForegroundColor Gray
    Write-Host "2. Download 'model_quantized.onnx'" -ForegroundColor Gray
    Write-Host "3. Save it to: VectorSearchApp/Models/all-MiniLM-L6-v2.onnx" -ForegroundColor Gray
    exit 1
}
