#!/usr/bin/env bash
set -euo pipefail

MODEL_TAG="qwen3.5:35b-a3b"
MODELS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)/models"
TEMPLATE_FILE="$MODELS_DIR/Modelfile.qwen3.5-35b-a3b"
TMP_FILE="$MODELS_DIR/.Modelfile.qwen3.5-35b-a3b.rendered"

if ! command -v ollama >/dev/null 2>&1; then
  echo "[error] ollama not found in PATH"
  exit 1
fi

if ollama list | awk '{print $1}' | grep -qx "$MODEL_TAG"; then
  echo "[ok] $MODEL_TAG is already installed"
  exit 0
fi

if [[ -z "${MODEL_SOURCE:-}" ]]; then
  echo "[error] MODEL_SOURCE is not set"
  echo "Set MODEL_SOURCE to GGUF source, e.g.:"
  echo "  export MODEL_SOURCE='hf.co/your-org/Qwen3.5-35B-A3B-GGUF:Q4_K_M'"
  exit 1
fi

if [[ ! -f "$TEMPLATE_FILE" ]]; then
  echo "[error] Modelfile template not found: $TEMPLATE_FILE"
  exit 1
fi

sed "s|\${MODEL_SOURCE}|${MODEL_SOURCE}|g" "$TEMPLATE_FILE" > "$TMP_FILE"

echo "[info] Creating $MODEL_TAG from MODEL_SOURCE=$MODEL_SOURCE"
ollama create "$MODEL_TAG" -f "$TMP_FILE"

rm -f "$TMP_FILE"
echo "[ok] Installed $MODEL_TAG"
