#!/bin/bash

# Enable strict mode
set -euo pipefail

# Default to HTTP
USE_HTTPS=false



# Parse arguments
for arg in "$@"; do
  if [[ "$arg" == "--https" ]]; then
    USE_HTTPS=true
  fi
done

# Resolve script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
AI_HUB_DIR="$(realpath "$SCRIPT_DIR/../ai-hub")"
CLIENT_DIR="$(realpath "$SCRIPT_DIR/../frontend")"

AI_HUB_HOST="0.0.0.0"
AI_HUB_PORT="8001"
APP_MODULE="app.main:app"

echo "--- Cleaning up existing processes ---"
# Kill existing uvicorn processes on the expected port
EXISTING_UVICORN_PID=$(lsof -ti tcp:${AI_HUB_PORT} || true)
if [ -n "$EXISTING_UVICORN_PID" ]; then
  echo "Killing existing process on port ${AI_HUB_PORT} (PID: $EXISTING_UVICORN_PID)"
  kill -9 "$EXISTING_UVICORN_PID"
fi

# Kill existing React frontend on port 8000
EXISTING_REACT_PID=$(lsof -ti tcp:8000 || true)
if [ -n "$EXISTING_REACT_PID" ]; then
  echo "Killing existing frontend process on port 8000 (PID: $EXISTING_REACT_PID)"
  kill -9 "$EXISTING_REACT_PID"
fi
pushd "$AI_HUB_DIR" > /dev/null

pip install -e .

SSL_ARGS=""
FRONTEND_ENV=""

if [ "$USE_HTTPS" = true ]; then
  echo "--- Generating self-signed SSL certificates ---"

  # Create a temporary directory for certs
  SSL_TEMP_DIR=$(mktemp -d)
  SSL_KEYFILE="${SSL_TEMP_DIR}/key.pem"
  SSL_CERTFILE="${SSL_TEMP_DIR}/cert.pem"

  # Generate self-signed certificate
  openssl req -x509 -nodes -days 1 -newkey rsa:2048 \
    -keyout "$SSL_KEYFILE" \
    -out "$SSL_CERTFILE" \
    -subj "/CN=localhost"

  # Cleanup function to remove certs on exit
  cleanup() {
    echo "--- Cleaning up SSL certificates ---"
    rm -rf "$SSL_TEMP_DIR"
  }
  trap cleanup EXIT

  SSL_ARGS="--ssl-keyfile $SSL_KEYFILE --ssl-certfile $SSL_CERTFILE"
  FRONTEND_ENV="HTTPS=true"
fi

# New step: Install frontend dependencies
echo "--- Installing frontend dependencies ---"
pushd "$CLIENT_DIR" > /dev/null
npm install
popd > /dev/null

echo "--- Starting AI Hub Server, React frontend, and backend proxy ---"

# Run backend and frontend concurrently
npx concurrently \
  --prefix "[{name}]" \
  --names "aihub,tts-frontend" \
  "LOG_LEVEL=DEBUG uvicorn $APP_MODULE --host $AI_HUB_HOST --log-level debug  --port $AI_HUB_PORT $SSL_ARGS --reload" \
  "cd $CLIENT_DIR && $FRONTEND_ENV GENERATE_SOURCEMAP=false HOST=0.0.0.0 PORT=8000 npm start"

popd > /dev/null
