#!/usr/bin/env bash
# Startup script for deploy (Render, VPS, etc.)
# Starts Docker Postgres when available, then runs migrations and the app.

set -e

# Start Docker Postgres if docker/docker compose are available (e.g. on VPS)
if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
    echo "Starting Docker Postgres..."
    docker compose up -d db
    # Wait for Postgres to accept connections (max 30s)
    for i in $(seq 1 30); do
        if docker compose exec -T db pg_isready -U "${POSTGRES_USER:-soulsync}" -d "${POSTGRES_DB:-soulsync_db}" 2>/dev/null; then
            echo "Postgres is ready"
            break
        fi
        if [ "$i" -eq 30 ]; then
            echo "⚠️  Postgres did not become ready in time"
            exit 1
        fi
        sleep 1
    done
else
    echo "Docker/docker compose not available (e.g. Render); assuming DB is already running"
fi

# This app requires PostgreSQL (uses ArrayField). Do not run with SQLite in production.
if [ -z "$DATABASE_URL" ]; then
    echo "❌ DATABASE_URL is not set. On Render: add a Postgres instance, then set DATABASE_URL in Environment (Internal Database URL)."
    exit 1
fi
echo "✅ DATABASE_URL is set, using PostgreSQL"

# Use python3 if python is not available
PYTHON=python
command -v python3 >/dev/null 2>&1 && PYTHON=python3

# Wait for DB to be reachable, then run migrations (retry for Render first-deploy / cold start)
echo "Running migrations..."
for i in $(seq 1 15); do
    if $PYTHON manage.py migrate --no-input; then
        echo "Migrations completed."
        break
    fi
    if [ "$i" -eq 15 ]; then
        echo "❌ Migrations failed after 15 attempts. Check DATABASE_URL and DB connectivity."
        exit 1
    fi
    echo "Waiting for database... attempt $i/15"
    sleep 3
done

# Collect static files at runtime (Render may not persist build staticfiles; required for admin CSS/JS)
echo "Collecting static files..."
$PYTHON manage.py collectstatic --noinput
echo "Static files collected."

# Start gunicorn (Render sets PORT; default 8000 for local)
PORT=${PORT:-8000}
exec gunicorn soul_sync.wsgi:application --bind 0.0.0.0:$PORT
