#!/usr/bin/env bash
# ElevenLabs Sound Effects Generator
# Usage: sfx.sh "description" [output_file] [duration_seconds] [prompt_influence]

set -euo pipefail
# shellcheck source=/dev/null
[ -f /root/clawd/.env ] && set -a && . /root/clawd/.env && set +a

DESCRIPTION="${1:-}"
OUTPUT="${2:-}"
DURATION="${3:-}"        # Optional: 0.5–30 seconds (auto if empty)
INFLUENCE="${4:-0.3}"    # Prompt influence 0–1

if [ -z "$DESCRIPTION" ]; then
  echo "Usage: $0 <description> [output_file] [duration_seconds] [prompt_influence]" >&2
  echo "" >&2
  echo "Examples:" >&2
  echo "  $0 \"thunder crack with rumbling echo\"" >&2
  echo "  $0 \"coffee shop ambience\" ambience.mp3 10" >&2
  echo "  $0 \"sword clash metallic ring\" sword.mp3 2 0.7" >&2
  exit 1
fi

if [ -z "${ELEVENLABS_API_KEY:-}" ]; then
  echo "Error: ELEVENLABS_API_KEY not set" >&2
  exit 1
fi

TEXT_JSON=$(echo "$DESCRIPTION" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read().rstrip()))')

if [ -n "$DURATION" ]; then
  BODY="{\"text\": ${TEXT_JSON}, \"duration_seconds\": ${DURATION}, \"prompt_influence\": ${INFLUENCE}}"
else
  BODY="{\"text\": ${TEXT_JSON}, \"prompt_influence\": ${INFLUENCE}}"
fi

HTTP_CODE=$(curl -s -o /tmp/elevenlabs_sfx_output.mp3 -w "%{http_code}" \
  -X POST "https://api.elevenlabs.io/v1/sound-generation" \
  -H "xi-api-key: ${ELEVENLABS_API_KEY}" \
  -H "Content-Type: application/json" \
  -d "$BODY")

if [ "$HTTP_CODE" != "200" ]; then
  echo "Error: API returned HTTP $HTTP_CODE" >&2
  cat /tmp/elevenlabs_sfx_output.mp3 >&2
  exit 1
fi

if [ -n "$OUTPUT" ]; then
  mv /tmp/elevenlabs_sfx_output.mp3 "$OUTPUT"
  echo "Saved to: $OUTPUT"
else
  echo "/tmp/elevenlabs_sfx_output.mp3"
fi
