#!/bin/sh
set -e

echo "Waiting for PostgreSQL at ${POSTGRES_HOST}:${POSTGRES_PORT}..."
until python -c "
import os, psycopg2, sys
try:
    psycopg2.connect(
        dbname=os.environ.get('POSTGRES_DB', 'tecvico'),
        user=os.environ.get('POSTGRES_USER', 'tecvico_user'),
        password=os.environ.get('POSTGRES_PASSWORD', ''),
        host=os.environ.get('POSTGRES_HOST', 'db'),
        port=os.environ.get('POSTGRES_PORT', '5432'),
    )
    sys.exit(0)
except Exception:
    sys.exit(1)
"; do
  echo "Database not ready. Retrying in 2 seconds..."
  sleep 2
done

echo "PostgreSQL is ready."

echo "Collecting static files..."
python manage.py collectstatic --noinput

echo "Running database migrations..."
python manage.py migrate --noinput

echo "Creating superuser if not exists..."
python manage.py ensure_superuser

echo "Starting application..."
exec "$@"
