#!/bin/bash
# Keep the model + embedding warm so a user request never pays the cold-start cost.
LOG=/var/log/stack-health.log
log() { echo "$(date -Is) warm: $*" >>"$LOG"; }

DB=/root/.9router/db/data.sqlite
KEY=$(python3 - "$DB" <<'PY' 2>/dev/null
import sqlite3,sys
c=sqlite3.connect(sys.argv[1])
cols=[r[1] for r in c.execute("pragma table_info(apiKeys)")]
row=c.execute("select * from apiKeys limit 1").fetchone()
print(row[cols.index('key')] if row else "")
PY
)

# 1) LLM provider connection (tiny completion)
if [ -n "$KEY" ]; then
  code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 25 -X POST \
    http://127.0.0.1:20128/v1/chat/completions \
    -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
    -d '{"model":"gemini/gemini-3.5-flash-lite","messages":[{"role":"user","content":"."}],"max_tokens":1}' 2>/dev/null)
  [ "$code" = "200" ] || log "llm warmup returned $code"
fi

# 2) embedding model (keeps bge-m3 resident)
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 25 -X POST \
  http://172.18.0.1:11434/api/embeddings -H 'Content-Type: application/json' \
  -d '{"model":"bge-m3:latest","prompt":"."}' 2>/dev/null)
[ "$code" = "200" ] || log "embed warmup returned $code"
