#!/bin/bash

if command -v ollama >/dev/null 2>&1; then
  echo "Starting Ollama server..."
  ollama serve &
  sleep 1
else
  echo "Ollama not installed in this image; skipping."
fi

# if ! ollama list | grep -q "qwen2.5:3b"; then
#     echo "Model qwen2.5:3b not found. Pulling..."
#     ollama pull qwen2.5:3b

# else
#     echo "Model qwen2.5:3b already exists. Skipping pull."
# fi

# #download embedding model
# if ! ollama list | grep -q "embeddinggemma:300m"; then
#     echo "Model embeddinggemma:300m not found. Pulling..."
#     ollama pull embeddinggemma:300m

# else
#     echo "Model embeddinggemma:300m already exists. Skipping pull."
# fi

# NLTK corpora are installed when the image is built (see Dockerfile).
# Bind mount overwrites /app; image site-packages may be stale vs mounted requirements.txt.
if [ -f /app/requirements.txt ]; then
  echo "Installing/updating Python deps from mounted /app/requirements.txt..."
  pip install --no-cache-dir -r /app/requirements.txt || {
    echo "ERROR: pip install -r /app/requirements.txt failed; fix deps and restart be0."
    exit 1
  }
fi

echo "Applying idempotent initiative DB migrations (008–014 incl. registration_otp_codes) if needed..."
python /app/scripts/apply_initiative_migrations.py || echo "WARNING: apply_initiative_migrations exited non-zero — check be0 logs (API may return 503 for evidence/artifacts until DB is fixed)."

echo "Starting FastAPI..."
if [ "${UVICORN_RELOAD:-0}" = "1" ]; then
  exec uvicorn main:app --host 0.0.0.0 --port 4402 --reload
else
  exec uvicorn main:app --host 0.0.0.0 --port 4402
fi
