param(
    [string]$OutputDir = "models/gguf/1c/devstral-small-2-24b-instruct-2512-q4_k_m",
    [int]$MaxAttempts = 200
)

$ErrorActionPreference = "Stop"

$RepoUrl = "https://huggingface.co/bartowski/mistralai_Devstral-Small-2-24B-Instruct-2512-GGUF/resolve/main"
$FileName = "mistralai_Devstral-Small-2-24B-Instruct-2512-Q4_K_M.gguf"
$ExpectedBytes = 14334438272
$OutputPath = Join-Path $OutputDir $FileName

New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null

for ($i = 1; $i -le $MaxAttempts; $i++) {
    $current = if (Test-Path -LiteralPath $OutputPath) {
        (Get-Item -LiteralPath $OutputPath).Length
    } else {
        0
    }

    if ($current -ge $ExpectedBytes) {
        break
    }

    Write-Host "Attempt $i, current bytes: $current / $ExpectedBytes"
    curl.exe `
        -L `
        -C - `
        --retry 10 `
        --retry-all-errors `
        --retry-delay 2 `
        --connect-timeout 30 `
        --speed-time 60 `
        --speed-limit 1024 `
        -o $OutputPath `
        "$RepoUrl/$FileName"
}

$final = if (Test-Path -LiteralPath $OutputPath) {
    (Get-Item -LiteralPath $OutputPath).Length
} else {
    0
}

if ($final -lt $ExpectedBytes) {
    throw "Download incomplete: $final / $ExpectedBytes bytes. Re-run this script to resume."
}

Write-Host "Download complete: $OutputPath"
