#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
PROJECT_DIR=$(cd -- "$SCRIPT_DIR/.." && pwd)

if [[ -f "$PROJECT_DIR/.env" ]]; then
  set -a
  source "$PROJECT_DIR/.env"
  set +a
fi

VOICE_ID=${ELEVENLABS_VOICE_ID:-${1:-}}
INPUT_JSON=${2:-$PROJECT_DIR/examples/script_mistakes_when_learning_english_v2_3min.json}
OUTPUT_AUDIO=${3:-$PROJECT_DIR/outputs/audio/monologue.mp3}
MODEL_ID=${ELEVENLABS_MODEL_ID:-eleven_flash_v2_5}
WITH_TIMESTAMPS=${ELEVENLABS_WITH_TIMESTAMPS:-1}
OUTPUT_TIMESTAMPS=${4:-${OUTPUT_AUDIO%.*}.timestamps.json}

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

if [[ -z "$VOICE_ID" ]]; then
  echo "Usage: generate_tts_audio.sh <voice_id> [input_json] [output_audio]" >&2
  echo "Or set ELEVENLABS_VOICE_ID in .env" >&2
  exit 1
fi

TMP_TEXT=$(mktemp)
TMP_JSON=$(mktemp)
trap 'rm -f "$TMP_TEXT" "$TMP_JSON"' EXIT

python3 "$SCRIPT_DIR/render_tts_input.py" "$INPUT_JSON" "$TMP_TEXT"

python3 - <<'PY' "$TMP_TEXT" "$TMP_JSON" "$MODEL_ID"
import json, sys
text_path, out_path, model_id = sys.argv[1], sys.argv[2], sys.argv[3]
text = open(text_path, encoding='utf-8').read()
payload = {
    "text": text,
    "model_id": model_id,
    "voice_settings": {
        "stability": 0.5,
        "similarity_boost": 0.75
    }
}
with open(out_path, 'w', encoding='utf-8') as f:
    json.dump(payload, f, ensure_ascii=False)
PY

mkdir -p "$(dirname "$OUTPUT_AUDIO")"

if [[ "$WITH_TIMESTAMPS" == "1" ]]; then
  TMP_RESPONSE=$(mktemp)
  trap 'rm -f "$TMP_TEXT" "$TMP_JSON" "$TMP_RESPONSE"' EXIT

  curl -sS -X POST "https://api.elevenlabs.io/v1/text-to-speech/${VOICE_ID}/with-timestamps" \
    -H "xi-api-key: ${ELEVENLABS_API_KEY}" \
    -H "Content-Type: application/json" \
    --data-binary "@$TMP_JSON" \
    --output "$TMP_RESPONSE"

  python3 - <<'PY' "$TMP_RESPONSE" "$OUTPUT_AUDIO" "$OUTPUT_TIMESTAMPS"
import base64, json, sys
resp_path, audio_path, timestamps_path = sys.argv[1:4]
with open(resp_path, encoding='utf-8') as f:
    data = json.load(f)
if 'audio_base64' not in data:
    print(json.dumps(data, ensure_ascii=False, indent=2), file=sys.stderr)
    raise SystemExit(1)
with open(audio_path, 'wb') as f:
    f.write(base64.b64decode(data['audio_base64']))
with open(timestamps_path, 'w', encoding='utf-8') as f:
    json.dump({
        'alignment': data.get('alignment'),
        'normalized_alignment': data.get('normalized_alignment')
    }, f, ensure_ascii=False, indent=2)
PY

  echo "Saved audio to $OUTPUT_AUDIO"
  echo "Saved timestamps to $OUTPUT_TIMESTAMPS"
else
  curl -sS -X POST "https://api.elevenlabs.io/v1/text-to-speech/${VOICE_ID}" \
    -H "xi-api-key: ${ELEVENLABS_API_KEY}" \
    -H "Content-Type: application/json" \
    --data-binary "@$TMP_JSON" \
    --output "$OUTPUT_AUDIO"

  echo "Saved audio to $OUTPUT_AUDIO"
fi
