#!/usr/bin/env bash
# TTS voice message sender: text → xAI TTS → OGG OPUS → Telegram voice
# Usage: tts-send.sh "text to speak" [voice_id]
set -euo pipefail

TEXT="$1"
VOICE="${2:-rex}"
LANG="${3:-ru}"

# Config
FFMPEG="$HOME/.local/bin/ffmpeg"
CCBOT_STATE="$HOME/.ccbot/state.json"
CCBOT_ENV="$HOME/.ccbot/.env"

# Read secrets from ccbot .env
TELEGRAM_BOT_TOKEN=$(grep '^TELEGRAM_BOT_TOKEN=' "$CCBOT_ENV" | cut -d= -f2)
XAI_API_KEY=$(grep '^XAI_API_KEY=' "$CCBOT_ENV" | cut -d= -f2)

# Resolve chat_id and thread_id from ccbot state
# Find the first active thread binding and its group_chat_id
THREAD_ID=$(python3 -c "
import json, sys
state = json.load(open('$CCBOT_STATE'))
bindings = state.get('thread_bindings', {})
group_ids = state.get('group_chat_ids', {})
for uid, threads in bindings.items():
    for tid, wid in threads.items():
        key = f'{uid}:{tid}'
        if key in group_ids:
            print(f'{group_ids[key]}:{tid}')
            sys.exit(0)
print('')
")

if [ -z "$THREAD_ID" ]; then
    echo "ERROR: No active thread binding found in ccbot state" >&2
    exit 1
fi

CHAT_ID="${THREAD_ID%%:*}"
MSG_THREAD_ID="${THREAD_ID##*:}"

# Temp files
TMPDIR=$(mktemp -d)
MP3_FILE="$TMPDIR/tts.mp3"
OGG_FILE="$TMPDIR/tts.ogg"
trap 'rm -rf "$TMPDIR"' EXIT

# Step 1: Generate speech via xAI TTS API
HTTP_CODE=$(curl -s -w "%{http_code}" -o "$MP3_FILE" \
    -X POST "https://api.x.ai/v1/tts" \
    -H "Authorization: Bearer $XAI_API_KEY" \
    -H "Content-Type: application/json" \
    -d "$(python3 -c "
import json, sys
print(json.dumps({'text': sys.argv[1], 'voice_id': sys.argv[2], 'language': sys.argv[3]}))
" "$TEXT" "$VOICE" "$LANG")")

if [ "$HTTP_CODE" != "200" ]; then
    echo "ERROR: xAI TTS API returned HTTP $HTTP_CODE" >&2
    cat "$MP3_FILE" >&2
    exit 1
fi

MP3_SIZE=$(wc -c < "$MP3_FILE")
if [ "$MP3_SIZE" -lt 1000 ]; then
    echo "ERROR: TTS response too small ($MP3_SIZE bytes), likely an error" >&2
    cat "$MP3_FILE" >&2
    exit 1
fi

# Step 2: Convert MP3 → OGG OPUS
"$FFMPEG" -i "$MP3_FILE" -c:a libopus -b:a 64k -vn "$OGG_FILE" -y -loglevel error

# Step 3: Send voice message to Telegram
RESPONSE=$(curl -s -F "chat_id=$CHAT_ID" \
    -F "message_thread_id=$MSG_THREAD_ID" \
    -F "voice=@$OGG_FILE" \
    "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendVoice")

OK=$(echo "$RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin).get('ok', False))")

if [ "$OK" = "True" ]; then
    echo "OK: Voice message sent to chat=$CHAT_ID thread=$MSG_THREAD_ID"
else
    echo "ERROR: Telegram API error: $RESPONSE" >&2
    exit 1
fi
