#!/bin/bash
# Switch the Rivet phone line between production and training mode
# Usage: ./training-mode.sh [on|off|status]

source /root/.env.rateright-phone

PHONE_ID="e595dd71-4918-4411-bebd-cfd529c66216"
PHONE_NUMBER="+61238205443"
PRODUCTION_ASSISTANT="e2a1e509-89d8-4c24-9d56-2c12f25321f0"  # RateRight Info Line
TRAINING_ASSISTANT="a668e7f2-2e1f-4409-80db-1c0f578c72b7"    # Sales Training - Sceptical Contractor

case "$1" in
  on)
    echo "🎯 Switching $PHONE_NUMBER to TRAINING MODE..."
    RESULT=$(curl -s -X PATCH "https://api.vapi.ai/phone-number/$PHONE_ID" \
      -H "Authorization: Bearer $VAPI_API_KEY" \
      -H "Content-Type: application/json" \
      -d "{\"assistantId\": \"$TRAINING_ASSISTANT\"}")
    
    CURRENT=$(echo "$RESULT" | node -e "const d=require('fs').readFileSync('/dev/stdin','utf8'); const r=JSON.parse(d); console.log(r.assistantId)")
    if [ "$CURRENT" = "$TRAINING_ASSISTANT" ]; then
      echo "✅ Training mode ON — call $PHONE_NUMBER to practice"
      echo "   The contractor persona will answer."
      echo "   Run './training-mode.sh off' when done."
    else
      echo "❌ Failed to switch. Response:"
      echo "$RESULT"
    fi
    ;;
    
  off)
    echo "📞 Switching $PHONE_NUMBER back to PRODUCTION..."
    RESULT=$(curl -s -X PATCH "https://api.vapi.ai/phone-number/$PHONE_ID" \
      -H "Authorization: Bearer $VAPI_API_KEY" \
      -H "Content-Type: application/json" \
      -d "{\"assistantId\": \"$PRODUCTION_ASSISTANT\"}")
    
    CURRENT=$(echo "$RESULT" | node -e "const d=require('fs').readFileSync('/dev/stdin','utf8'); const r=JSON.parse(d); console.log(r.assistantId)")
    if [ "$CURRENT" = "$PRODUCTION_ASSISTANT" ]; then
      echo "✅ Production mode restored — Info Line is live"
    else
      echo "❌ Failed to switch. Response:"
      echo "$RESULT"
    fi
    ;;
    
  status)
    echo "📊 Checking current mode for $PHONE_NUMBER..."
    RESULT=$(curl -s "https://api.vapi.ai/phone-number/$PHONE_ID" \
      -H "Authorization: Bearer $VAPI_API_KEY")
    
    CURRENT=$(echo "$RESULT" | node -e "const d=require('fs').readFileSync('/dev/stdin','utf8'); const r=JSON.parse(d); console.log(r.assistantId)")
    
    if [ "$CURRENT" = "$TRAINING_ASSISTANT" ]; then
      echo "🎯 TRAINING MODE — contractor roleplay active"
    elif [ "$CURRENT" = "$PRODUCTION_ASSISTANT" ]; then
      echo "📞 PRODUCTION MODE — Info Line active"
    else
      echo "⚠️  Unknown assistant: $CURRENT"
    fi
    ;;
    
  *)
    echo "Usage: ./training-mode.sh [on|off|status]"
    echo ""
    echo "  on     — Switch to training mode (sceptical contractor)"
    echo "  off    — Switch back to production (Info Line)"
    echo "  status — Check current mode"
    ;;
esac
