#!/bin/bash
set -e

# Определяем окружение (по умолчанию production)
ENVIRONMENT=${ENVIRONMENT:-production}

echo "Starting in $ENVIRONMENT mode..."

if [ -d "logs" ]; then
  echo "Directory logs already exists."
else
  echo "Creating logs directory..."
  mkdir -p logs
fi

echo "Waiting for PostgreSQL..."
until PGPASSWORD=$DB_PASSWORD psql -h "$DB_HOST" -U "$DB_USER" -d "$DB_NAME" -c '\q' 2>/dev/null; do
  echo "PostgreSQL is unavailable - sleeping"
  sleep 1
done
echo "PostgreSQL started"

echo "Running migrations..."
uv run python manage.py migrate --noinput

if [ "$ENVIRONMENT" = "production" ]; then
    echo "Collecting static files..."
    uv run python manage.py collectstatic --noinput
fi

if [ "$ENVIRONMENT" = "development" ]; then
    echo "Starting Django development server..."
    exec uv run python manage.py runserver 0.0.0.0:8000
else
    echo "Starting Gunicorn..."
    exec uv run gunicorn --bind 0.0.0.0:8000 \
        --workers ${GUNICORN_WORKERS:-3} \
        --timeout ${GUNICORN_TIMEOUT:-120} \
        dbapp.wsgi:application
fi
