#!/usr/bin/env bash
# T-04 — Build a multilingual voice assistant (companion driver)
# Ask Evergreen AI a question, translate the answer with Linga, register a
# voice print with Speech, synthesize the translation in that voice, then
# kill and restart linga-service to expose its hidden role in TTS.
set -uo pipefail
source /tmp/inaya_env.sh
export INAYA_LABS_ENVIRONMENT=local

export AUTH_URL="http://127.0.0.1:40004"
export EVG_URL="http://127.0.0.1:40071"
export LINGA_URL="http://127.0.0.1:40065"
export SPEECH_URL="http://127.0.0.1:40161"
export INAYA_API_KEY="$INAYA_LABS_API_KEY"
export INAYA_APP_KEY="$INAYA_LABS_APP_KEY"
export TENANT_ID="${TENANT_ID:-qa-tenant-t02}"
cd "$(dirname "$0")/../../../../.."

KEYS=(-H "x-api-key: ${INAYA_API_KEY}" -H "x-client-app-key: ${INAYA_APP_KEY}")
sign_in() {
  curl -sf -X POST "${AUTH_URL}/v3/auth/qa/login" "${KEYS[@]}" \
    -H "Content-Type: application/json" \
    -d "{\"device_id\": \"t04-device-01\", \"locale\": \"en-US\", \"tenant_id\": \"${TENANT_ID}\", \"username\": \"$1\"}" \
    | python3 -c 'import json,sys; print(json.load(sys.stdin)["token"])'
}
TOKEN=$(sign_in t04-amara)
echo "═══ T-04 multilingual voice assistant · tenant ${TENANT_ID} ═══"

# 1. ask the assistant
SESS=$(curl -sf -m 180 -X POST "${EVG_URL}/v3/sessions" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -H "Content-Type: application/json" \
  -d '{"system_prompt":"You are a concise community-garden assistant. Answer in one or two short sentences.","temperature":0.2,"required_modalities":["Text"],"selection_criteria":[{"Model":{"optionality":"MustHave","name":"Llama3_2_1B_Q4"}}]}')
SESSION_ID=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["ai_session_id"])' <<< "${SESS}")
REPLY=$(curl -sf -m 240 -X POST "${EVG_URL}/v3/sessions/${SESSION_ID}/chat-messages" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -F "user_message=What should we plant this week? It is late September.")
ANSWER=$(python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["content"][0]["Text"])' <<< "${REPLY}")
echo "assistant: ${ANSWER}"
echo "✔ checkpoint 1 — session answered a gardening question"

# 2. translate to Spanish
TRANSLATED=$(curl -sf -m 180 -X POST "${LINGA_URL}/v3/translation/translate" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -H "Content-Type: application/json" \
  -d "$(python3 - "$ANSWER" <<'EOF'
import json, sys
print(json.dumps({"source": {"locale": "en-US"}, "target": {"locale": "es-ES"}, "text": sys.argv[1]}))
EOF
)" | python3 -c 'import json,sys; print(json.load(sys.stdin)["translated_text"])')
echo "es: ${TRANSLATED}"
echo "✔ checkpoint 2 — answer translated for the Spanish-speaking volunteers"

# 3. register the voice print
say -o /tmp/t04-voice.aiff \
  "Hi, this is Amara. I keep the community garden notes, and I speak three languages."
afconvert -f WAVE -d LEI16@22050 /tmp/t04-voice.aiff /tmp/t04-voice.wav
VOICEPRINT_PATH=$(curl -sf -m 300 -X POST "${SPEECH_URL}/v3/voice-prints" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -F "file=@/tmp/t04-voice.wav" \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["voice_print_wav_path"])')
echo "voice print: ${VOICEPRINT_PATH}"
echo "✔ checkpoint 3 — voice print registered and persisted to the CDN"

# 4. synthesize the translation in Amara's voice
curl -sf -m 320 -o /tmp/t04-es.mp3 \
  -X POST "${SPEECH_URL}/v3/text-to-speech" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -H "Content-Type: application/json" \
  -d "$(python3 - "$TRANSLATED" "$VOICEPRINT_PATH" <<'EOF'
import json, sys
print(json.dumps({"input": sys.argv[1], "reference_voiceprint_path": sys.argv[2]}))
EOF
)"
DUR=$(ffprobe -v error -show_entries format=duration -of csv=p=0 /tmp/t04-es.mp3)
python3 -c "d=float('${DUR}'); assert d > 1.0, d"
echo "✔ checkpoint 4 — ${DUR}s of Spanish speech synthesized in the registered voice"

# 5. failure injection: kill linga, expose the hidden TTS dependency
pkill -x linga-service && echo "   linga killed"
sleep 1
curl -s -o /dev/null --max-time 5 -X POST "${LINGA_URL}/v3/translation/translate" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -H "Content-Type: application/json" \
  -d '{"source":{"locale":"en-US"},"target":{"locale":"ar-SA"},"text":"Water the tomatoes twice a week."}' \
  || echo "   translate during outage: connection refused"
CODE=$(curl -s -o /dev/null --max-time 60 -w "%{http_code}" \
  -X POST "${SPEECH_URL}/v3/text-to-speech" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -H "Content-Type: application/json" \
  -d "$(python3 - "$TRANSLATED" "$VOICEPRINT_PATH" <<'EOF'
import json, sys
print(json.dumps({"input": sys.argv[1], "reference_voiceprint_path": sys.argv[2]}))
EOF
)")
test "${CODE}" != "200" && echo "✔ checkpoint 5a — one killed service broke two pipelines (TTS needs Linga for language detection)"
source /tmp/inaya_env.sh; export INAYA_LABS_ENVIRONMENT=local
nohup "$(pwd)/target/debug/linga-service" > /tmp/linga-service.log 2>&1 &
sleep 3
AR=$(curl -sf -m 180 -X POST "${LINGA_URL}/v3/translation/translate" \
  -H "Authorization: Bearer ${TOKEN}" "${KEYS[@]}" \
  -H "Content-Type: application/json" \
  -d '{"source":{"locale":"en-US"},"target":{"locale":"ar-SA"},"text":"Water the tomatoes twice a week."}' \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["translated_text"])')
echo "ar: ${AR}"
echo "✔ checkpoint 5b — translator restarted, Arabic flowing again"

echo "═══ T-04 complete ═══"
