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

cd "$(dirname "$0")/.."

MODEL="${OLLAMA_MODEL:-qwen2.5:7b}"
OLLAMA_WAIT_SECONDS="${OLLAMA_WAIT_SECONDS:-180}"
PULL_WAIT_SECONDS="${OLLAMA_PULL_WAIT_SECONDS:-1800}"

compose() {
  docker compose "$@"
}

wait_for_ollama() {
  local deadline=$((SECONDS + OLLAMA_WAIT_SECONDS))
  while [ "$SECONDS" -lt "$deadline" ]; do
    if compose exec -T ollama ollama list >/dev/null 2>&1; then
      return 0
    fi
    sleep 3
  done
  return 1
}

model_present() {
  compose exec -T ollama ollama list 2>/dev/null | awk 'NR>1 {print $1}' | grep -Fx "$MODEL" >/dev/null 2>&1
}

wait_for_model() {
  local deadline=$((SECONDS + PULL_WAIT_SECONDS))
  while [ "$SECONDS" -lt "$deadline" ]; do
    if model_present; then
      return 0
    fi
    sleep 5
  done
  return 1
}

echo "Starting Ollama service..."
compose up -d ollama

if ! wait_for_ollama; then
  echo "Ollama did not become ready within ${OLLAMA_WAIT_SECONDS}s."
  compose logs --tail=200 ollama || true
  exit 1
fi

echo "Ollama is responding."

if model_present; then
  echo "Model already present: $MODEL"
else
  echo "Pulling Ollama model: $MODEL"
  compose exec -T ollama ollama pull "$MODEL" || {
    echo "Model pull command failed."
    compose logs --tail=200 ollama || true
    exit 1
  }
fi

if ! wait_for_model; then
  echo "Model ${MODEL} did not appear within ${PULL_WAIT_SECONDS}s."
  compose exec -T ollama ollama list || true
  exit 1
fi

echo "Ollama model ready: $MODEL"

echo "Restarting AI service so it can use the ready Ollama model."
compose up -d ai-service

if ! compose ps ai-service --format '{{.State}}' 2>/dev/null | head -n 1 | tr '[:upper:]' '[:lower:]' | grep -qx 'running'; then
  echo "AI service is not running after Ollama warmup."
  compose logs --tail=200 ai-service || true
  exit 1
fi

echo "Ollama warmup complete."
