#!/usr/bin/env bash
# ElevenLabs Music Generator
# Usage: music.sh "prompt" [output_file]

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

PROMPT="${1:-}"
OUTPUT="${2:-}"

if [ -z "$PROMPT" ]; then
  echo "Usage: $0 <prompt> [output_file]" >&2
  echo "" >&2
  echo "Examples:" >&2
  echo "  $0 \"upbeat electronic dance track with synth leads\"" >&2
  echo "  $0 \"calm acoustic guitar for a coffee shop\" bg.mp3" >&2
  echo "  $0 \"epic orchestral cinematic trailer music\"" >&2
  echo "" >&2
  echo "Tips:" >&2
  echo "  - Describe genre, mood, instruments, and tempo" >&2
  echo "  - Do NOT reference specific artists or copyrighted songs" >&2
  exit 1
fi

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

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

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

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

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