#!/bin/bash
# Jibri Finalize Script
# Wird aufgerufen wenn eine Aufzeichnung beendet ist
# Uploaded die Aufzeichnung zu MinIO und benachrichtigt das Backend

set -e

RECORDINGS_DIR="$1"
RECORDING_NAME=$(basename "$RECORDINGS_DIR")

echo "[Finalize] Starting finalization for: $RECORDING_NAME"
echo "[Finalize] Recordings directory: $RECORDINGS_DIR"

# Finde die Aufzeichnungsdatei
RECORDING_FILE=$(find "$RECORDINGS_DIR" -name "*.mp4" | head -1)

if [ -z "$RECORDING_FILE" ]; then
    echo "[Finalize] ERROR: No MP4 file found in $RECORDINGS_DIR"
    exit 1
fi

echo "[Finalize] Found recording file: $RECORDING_FILE"
FILE_SIZE=$(stat -c%s "$RECORDING_FILE" 2>/dev/null || stat -f%z "$RECORDING_FILE")
echo "[Finalize] File size: $FILE_SIZE bytes"

# MinIO Upload mit mc (MinIO Client)
MINIO_ALIAS="minio"
BUCKET="${MINIO_BUCKET:-breakpilot-recordings}"
DEST_PATH="recordings/${RECORDING_NAME}/video.mp4"

# MinIO Client konfigurieren (wenn noch nicht konfiguriert)
if ! mc alias list | grep -q "$MINIO_ALIAS"; then
    echo "[Finalize] Configuring MinIO client..."
    mc alias set "$MINIO_ALIAS" "http://${MINIO_ENDPOINT:-minio:9000}" \
        "${MINIO_ACCESS_KEY:-minioadmin}" \
        "${MINIO_SECRET_KEY:-minioadmin}"
fi

# Bucket erstellen falls nicht vorhanden
mc mb --ignore-existing "${MINIO_ALIAS}/${BUCKET}"

# Upload
echo "[Finalize] Uploading to MinIO: ${BUCKET}/${DEST_PATH}"
mc cp "$RECORDING_FILE" "${MINIO_ALIAS}/${BUCKET}/${DEST_PATH}"

if [ $? -eq 0 ]; then
    echo "[Finalize] Upload successful!"

    # Audio extrahieren fuer Transkription
    AUDIO_FILE="${RECORDINGS_DIR}/audio.wav"
    echo "[Finalize] Extracting audio for transcription..."
    ffmpeg -i "$RECORDING_FILE" -vn -acodec pcm_s16le -ar 16000 -ac 1 "$AUDIO_FILE" -y 2>/dev/null

    if [ -f "$AUDIO_FILE" ]; then
        AUDIO_DEST_PATH="recordings/${RECORDING_NAME}/audio.wav"
        mc cp "$AUDIO_FILE" "${MINIO_ALIAS}/${BUCKET}/${AUDIO_DEST_PATH}"
        echo "[Finalize] Audio extracted and uploaded: ${AUDIO_DEST_PATH}"
    fi

    # Backend Webhook benachrichtigen
    if [ -n "$BACKEND_WEBHOOK_URL" ]; then
        echo "[Finalize] Notifying backend webhook..."
        METADATA_FILE=$(find "$RECORDINGS_DIR" -name "*.json" | head -1)

        WEBHOOK_PAYLOAD=$(cat <<EOF
{
    "event": "recording_completed",
    "recording_name": "${RECORDING_NAME}",
    "storage_path": "${DEST_PATH}",
    "audio_path": "recordings/${RECORDING_NAME}/audio.wav",
    "file_size_bytes": ${FILE_SIZE},
    "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOF
)

        curl -X POST "$BACKEND_WEBHOOK_URL" \
            -H "Content-Type: application/json" \
            -d "$WEBHOOK_PAYLOAD" \
            --max-time 30 \
            || echo "[Finalize] WARNING: Webhook notification failed"
    fi

    # Lokale Dateien aufraeumen
    echo "[Finalize] Cleaning up local files..."
    rm -rf "$RECORDINGS_DIR"

    echo "[Finalize] Finalization completed successfully!"
else
    echo "[Finalize] ERROR: Upload failed!"
    exit 1
fi
