#!/bin/sh
set -eu

: "${TTSMINT_API_KEY:?Set TTSMINT_API_KEY in your trusted shell or secret manager}"
tmp=$(mktemp "./speech.mp3.XXXXXX")
trap 'rm -f "$tmp"' EXIT HUP INT TERM

response_meta=$(curl --silent --show-error --connect-timeout 10 --max-time 60 --output "$tmp" --write-out '%{http_code} %{content_type}' \
  --request POST 'https://ttsmint.com/v1/audio/speech' \
  --header "Authorization: Bearer $TTSMINT_API_KEY" \
  --header 'Content-Type: application/json' \
  --header 'Accept: audio/mpeg' \
  --data-binary @tts-reader-request.json)
status=${response_meta%% *}
content_type=${response_meta#* }

if [ "$status" != 200 ] || [ "${content_type%%;*}" != 'audio/mpeg' ]; then
  cat "$tmp" >&2
  echo 'Check the JSON error.code above; the body was not saved as MP3.' >&2
  exit 1
fi
if [ ! -s "$tmp" ]; then
  echo 'The server returned an empty MP3; the existing output was left unchanged.' >&2
  exit 1
fi

mv -f "$tmp" speech.mp3
trap - EXIT HUP INT TERM
