#!/usr/bin/env bash
# Idempotent symlinks: shared vendor weights -> per-user ~/.cache (torch + CLIP).
# See VENDOR_MODELS.md for vendor layout and download URLs.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENDOR_MODELS="${VENDOR_MODELS:-/opt/vendor/models/office_vlm}"
TORCH_HOME="${TORCH_HOME:-${HOME}/.cache/torch}"
CLIP_DIR="${CLIP_DIR:-${HOME}/.cache/clip}"

FRCNN_NAME="fasterrcnn_resnet50_fpn_v2_coco-dd69338a.pth"
CLIP_NAME="ViT-B-32.pt"

log() { echo "[office_vlm/models] $*"; }

link_if_missing() {
  local src="$1" dst="$2"
  if [[ ! -f "${src}" ]]; then
    log "WARN: vendor file missing (skip): ${src}"
    return 0
  fi
  if [[ -e "${dst}" ]]; then
    return 0
  fi
  mkdir -p "$(dirname "${dst}")"
  ln -sf "${src}" "${dst}"
  log "linked ${dst} -> ${src}"
}

mkdir -p "${TORCH_HOME}/hub/checkpoints" "${CLIP_DIR}"

link_if_missing \
  "${VENDOR_MODELS}/torch/hub/checkpoints/${FRCNN_NAME}" \
  "${TORCH_HOME}/hub/checkpoints/${FRCNN_NAME}"

link_if_missing \
  "${VENDOR_MODELS}/clip/${CLIP_NAME}" \
  "${CLIP_DIR}/${CLIP_NAME}"

if [[ -f "${VENDOR_MODELS}/torch/hub/checkpoints/${FRCNN_NAME}" ]] \
  && [[ -f "${VENDOR_MODELS}/clip/${CLIP_NAME}" ]]; then
  log "cache ready (vendor)"
else
  log "vendor incomplete — nodes will download on first clip.load / torchvision weights"
fi
