#!/bin/bash

# Resolve script directory and change to ai-hub root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR/.."

# --- 0. Load environment variables from .env file ---
# This ensures any necessary credentials or configurations are loaded.
if [ -f .env ]; then
  echo "Loading environment variables from .env"
  export $(grep -v '^#' .env | xargs)
fi
export LOG_LEVEL=DEBUG

# --- 1. Define variables and configurations ---
BASE_URL="http://127.0.0.1:8000"
STT_ENDPOINT="/stt/transcribe"
API_URL="${BASE_URL}${STT_ENDPOINT}"

# --- 2. Start the FastAPI Server in the Background ---
echo "--- Starting AI Hub Server ---"
uvicorn app.main:app --host 127.0.0.1 --port 8000 &
SERVER_PID=$!

# Define a function to shut down the server and clean up.
cleanup() {
  echo ""
  echo "--- Shutting Down Server (PID: $SERVER_PID) ---"
  kill $SERVER_PID
}
trap cleanup EXIT

# --- 3. Wait for the server to be ready ---
echo "Waiting for server to initialize..."
for i in {1..20}; do
  if curl --fail --silent "$BASE_URL" &> /dev/null; then
    echo "✅ Server is ready."
    break
  fi
  sleep 1
  if [ "$i" -eq 20 ]; then
    echo "❌ Error: Server failed to start in time. Exiting."
    exit 1
  fi
done

# --- 4. Prepare the audio file for testing ---
echo ""
echo "--- Preparing audio file for testing ---"
# Check if a file path was provided as an argument
if [ -z "$1" ]; then
  echo "❌ Error: No audio file path provided."
  echo "Usage: $0 /path/to/your/audio.wav"
  exit 1
fi

TEMP_AUDIO_FILE="$1"
if [ ! -f "$TEMP_AUDIO_FILE" ]; then
  echo "❌ Error: The specified file '$TEMP_AUDIO_FILE' does not exist."
  exit 1
fi
echo "✅ Using provided audio file: $TEMP_AUDIO_FILE"
echo ""

# --- 5. Test a successful transcription ---
echo "--- Testing successful transcription with valid audio file ---"
# We now explicitly specify the MIME type for the file using the curl -F flag syntax.
# We also use the -f, --fail flag to ensure curl returns an error code on HTTP 4xx/5xx status.
curl -s -f -X POST "$API_URL" \
  -H "Content-Type: multipart/form-data" \
  -F "audio_file=@$TEMP_AUDIO_FILE;type=audio/wav" | jq '.'

# Check the exit status of the curl command
# The return code is now more reliable thanks to the `-f` flag.
if [ ${PIPESTATUS[0]} -eq 0 ]; then
  echo ""
  echo "✅ Success! Received a valid transcription response."
else
  echo ""
  echo "❌ Failed to get a valid transcription response. Check the server logs for details."
fi
echo ""

# --- Tests complete. ---
