#!/bin/bash
set -e

echo "==============================="
echo "Starting Codeflash Services"
echo "==============================="

# Initialize PostgreSQL if needed
if [ ! -f "/var/lib/postgresql/data/PG_VERSION" ]; then
  echo "Initializing PostgreSQL database..."
  su - postgres -c "initdb -D /var/lib/postgresql/data"

  # Configure PostgreSQL
  echo "Configuring PostgreSQL..."
  cat >> /var/lib/postgresql/data/postgresql.conf <<EOF
listen_addresses = '*'
port = 5432
max_connections = 100
shared_buffers = 128MB
EOF

  cat >> /var/lib/postgresql/data/pg_hba.conf <<EOF
host    all             all             0.0.0.0/0               md5
host    all             all             ::0/0                   md5
EOF
fi

# Start PostgreSQL temporarily to ensure user and database exist
echo "Starting PostgreSQL for setup..."
su - postgres -c "pg_ctl -D /var/lib/postgresql/data start -o '-c logging_collector=off'"

# Wait for PostgreSQL to be ready
echo "Waiting for PostgreSQL to be ready..."
for i in {1..30}; do
  if su - postgres -c "pg_isready" > /dev/null 2>&1; then
    echo "PostgreSQL is ready!"
    break
  fi
  sleep 1
done

# Check if codeflash user exists, create if not
USER_EXISTS=$(su - postgres -c "psql -tAc \"SELECT 1 FROM pg_roles WHERE rolname='codeflash'\"" 2>/dev/null || echo "0")
if [ "$USER_EXISTS" != "1" ]; then
  echo "Creating database user and database..."
  su - postgres -c "psql -c \"CREATE USER codeflash WITH PASSWORD 'codeflash';\""
  su - postgres -c "psql -c \"CREATE DATABASE codeflash OWNER codeflash;\""
  su - postgres -c "psql -c \"GRANT ALL PRIVILEGES ON DATABASE codeflash TO codeflash;\""
  echo "User and database created successfully!"
else
  echo "Database user already exists, skipping creation."
fi

# Stop PostgreSQL so supervisord can start it properly
echo "Stopping temporary PostgreSQL instance..."
su - postgres -c "pg_ctl -D /var/lib/postgresql/data stop -w"
sleep 2

# Set default DATABASE_URL if not provided
export DATABASE_URL="${DATABASE_URL:-postgresql://codeflash:codeflash@localhost:5432/codeflash}"

# Auto-generate SECRET_KEY if not provided
if [ -z "$SECRET_KEY" ]; then
  echo "⚠️  SECRET_KEY not provided, generating random key..."
  export SECRET_KEY=$(openssl rand -hex 32)
  echo "✓ Generated SECRET_KEY"
fi

# Set default URLs if not provided
export NEXT_PUBLIC_APP_URL="${NEXT_PUBLIC_APP_URL:-http://localhost:3000}"
export WEBAPP_URL="${WEBAPP_URL:-http://localhost:3000}"
export CODEFLASH_CFAPI_URL="${CODEFLASH_CFAPI_URL:-http://localhost:3001}"

echo ""
echo "Starting services with supervisord..."
echo ""

# Start supervisord in background
/usr/bin/supervisord -c /etc/supervisord.conf &
SUPERVISOR_PID=$!

# Wait for PostgreSQL to be ready under supervisord
echo "Waiting for PostgreSQL to start under supervisord..."
sleep 10

# Run database initialization (migrations and API key creation)
/app/init-db.sh

# Keep supervisord running
wait $SUPERVISOR_PID