#!/bin/bash
set -e

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

echo "Starting in $ENVIRONMENT mode..."

# Ждем PostgreSQL
echo "Waiting for PostgreSQL..."
while ! nc -z $DB_HOST $DB_PORT; do
  sleep 0.1
done
echo "PostgreSQL started"

# Выполняем миграции
echo "Running migrations..."
python manage.py migrate --noinput

# Собираем статику (только для production)
if [ "$ENVIRONMENT" = "production" ]; then
    echo "Collecting static files..."
    python manage.py collectstatic --noinput
fi

# Запускаем сервер в зависимости от окружения
if [ "$ENVIRONMENT" = "development" ]; then
    echo "Starting Django development server..."
    exec python manage.py runserver 0.0.0.0:8000
else
    echo "Starting Gunicorn..."
    exec gunicorn --bind 0.0.0.0:8000 \
        --workers ${GUNICORN_WORKERS:-3} \
        --timeout ${GUNICORN_TIMEOUT:-120} \
        --reload \
        dbapp.wsgi:application
fi
