#!/usr/bin/env bash
# Pulls latest vocab, migrates ai_diagnoses, copies ANTHROPIC_API_KEY
# from math, flips the tutor flag on, reloads.
set -e

cd /var/www/html/vocabapi

echo "=== git pull ==="
git pull --ff-only 2>&1 | tail -3

echo ""
echo "=== migrate (creates ai_diagnoses) ==="
php artisan migrate --force 2>&1 | tail -5

echo ""
echo "=== Copying ANTHROPIC_API_KEY from math .env ==="
KEY=$(grep ^ANTHROPIC_API_KEY= /var/www/html/mathapi/.env | cut -d= -f2-)
if [ -z "$KEY" ]; then
  echo "ERROR: no ANTHROPIC_API_KEY in math .env"
  exit 1
fi
echo "Key length: ${#KEY}"

upsert() {
  local KEY_NAME="$1"
  local VAL="$2"
  if grep -q "^${KEY_NAME}=" .env; then
    # macOS sed is BSD, Ubuntu is GNU — escape | so the secret can contain almost anything
    sed -i "s|^${KEY_NAME}=.*|${KEY_NAME}=${VAL}|" .env
  else
    printf "%s=%s\n" "${KEY_NAME}" "${VAL}" >> .env
  fi
}

upsert ANTHROPIC_API_KEY "$KEY"
upsert ANTHROPIC_MODEL    "claude-haiku-4-5-20251001"
upsert VOCAB_TUTOR_ENABLED "true"
upsert ANTHROPIC_TIMEOUT  "10"
upsert ANTHROPIC_MAX_TOKENS "400"

echo ""
echo "=== Verifying ==="
grep -E '^(ANTHROPIC_|VOCAB_TUTOR_)' .env | sed -E 's/(API_KEY)=.*/\1=<set>/'

echo ""
echo "=== Cache + reload ==="
php artisan config:cache 2>&1 | tail -1
systemctl reload apache2
echo "apache reloaded"

echo ""
echo "=== Route sanity ==="
php artisan route:list --path=api/questions 2>&1 | head -5

echo ""
echo "=== Smoke: ai_diagnoses table exists ==="
DBPASS=$(grep ^DB_PASSWORD /var/www/html/mathapi/.env | cut -d= -f2-)
mysql -uroot -p"$DBPASS" vocab -Nse "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='vocab' AND table_name='ai_diagnoses';" 2>/dev/null | awk '{print "  ai_diagnoses table count: "$1}'

echo ""
echo "=== Rebuilding Flutter web (background, ~80s) ==="
nohup bash /tmp/install-flutter-and-build.sh > /tmp/build-tutor.log 2>&1 &
echo "  PID $!"
