#!/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 ---
if [ -f .env ]; then
  echo "Loading environment variables from .env"
  export $(grep -v '^#' .env | xargs)
fi
export LOG_LEVEL=DEBUG

API_URL="http://localhost:8000/documents"
DEFAULT_MODEL="gemini"
CURRENT_MODEL=""

# --- 1. Check for Dependencies ---
if ! command -v jq &> /dev/null; then
    echo "❌ 'jq' is not installed. Please install it to run this script."
    exit 1
fi

# --- 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=$!

cleanup() {
    echo ""
    echo "--- Shutting Down Server (PID: $SERVER_PID) ---"
    kill $SERVER_PID
}
trap cleanup EXIT

echo "Server started with PID: $SERVER_PID. Waiting for it to initialize..."
sleep 5

BASE_URL="http://localhost:8000"

# --- 3. Get TEST_TEXT from CLI argument ---
if [ -z "$1" ]; then
  echo "❌ No input text provided."
  echo "Usage: $0 \"Your text to send to /speech\""
  exit 1
fi
TEST_TEXT="$1"

# Create a temporary file to store the JSON payload
TEMP_JSON_FILE=$(mktemp)
cat > "$TEMP_JSON_FILE" << EOF
{
  "text": "$TEST_TEXT"
}
EOF

# --- Test streaming mode ---
echo ""
echo "--- Testing streaming mode for /speech endpoint ---"
STREAM_OUTPUT_FILE="data/speech_stream.wav"
curl -s -X POST "$BASE_URL/speech?stream=true" \
  -H "Content-Type: application/json" \
  --data "@$TEMP_JSON_FILE" \
  --output "$STREAM_OUTPUT_FILE"

if [ -f "$STREAM_OUTPUT_FILE" ]; then
  echo "✅ Success! Streaming audio saved to $STREAM_OUTPUT_FILE"
else
  echo "❌ Failed to get streaming audio"
fi

rm "$TEMP_JSON_FILE"
echo ""
echo "--- Tests complete. ---"
