#!/bin/bash
# download_whisper_model.sh
# Xcode pre-build script: downloads distil-whisper CoreML model if not present.
# Only runs once — subsequent builds skip it if the weight files already exist.

set -euo pipefail

MODEL_NAME="distil-whisper_distil-large-v3_594MB"
MODEL_DIR="${SRCROOT}/LockInBroMobile/${MODEL_NAME}"
HF_BASE="https://huggingface.co/argmaxinc/whisperkit-coreml/resolve/main/${MODEL_NAME}"

# Xcode checks outputPaths before running this script, but double-check here too.
if [ -f "${MODEL_DIR}/AudioEncoder.mlmodelc/weights/weight.bin" ] && \
   [ -f "${MODEL_DIR}/TextDecoder.mlmodelc/weights/weight.bin" ]; then
    echo "Whisper model already present — skipping download."
    exit 0
fi

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  Downloading distil-whisper model (~600 MB, one-time)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

FILES=(
    "config.json"
    "generation_config.json"
    "AudioEncoder.mlmodelc/metadata.json"
    "AudioEncoder.mlmodelc/model.mil"
    "AudioEncoder.mlmodelc/coremldata.bin"
    "AudioEncoder.mlmodelc/analytics/coremldata.bin"
    "AudioEncoder.mlmodelc/weights/weight.bin"
    "MelSpectrogram.mlmodelc/metadata.json"
    "MelSpectrogram.mlmodelc/model.mil"
    "MelSpectrogram.mlmodelc/coremldata.bin"
    "MelSpectrogram.mlmodelc/analytics/coremldata.bin"
    "MelSpectrogram.mlmodelc/weights/weight.bin"
    "TextDecoder.mlmodelc/metadata.json"
    "TextDecoder.mlmodelc/model.mil"
    "TextDecoder.mlmodelc/coremldata.bin"
    "TextDecoder.mlmodelc/analytics/coremldata.bin"
    "TextDecoder.mlmodelc/weights/weight.bin"
)

TOTAL=${#FILES[@]}
INDEX=0

for file in "${FILES[@]}"; do
    INDEX=$((INDEX + 1))
    dest="${MODEL_DIR}/${file}"
    mkdir -p "$(dirname "$dest")"
    if [ ! -f "$dest" ]; then
        echo "[${INDEX}/${TOTAL}] Downloading ${file}..."
        curl -L --retry 3 --retry-delay 2 --progress-bar \
             -o "$dest" "${HF_BASE}/${file}"
    else
        echo "[${INDEX}/${TOTAL}] Already exists: ${file}"
    fi
done

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  Model download complete. Build continuing..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
