#!/usr/bin/env bash
# Exit on error
set -o errexit

# Build script for Render deployment

# Use python3 if python is not available (e.g. some Render/images)
PYTHON=python
command -v python3 >/dev/null 2>&1 && PYTHON=python3
command -v python >/dev/null 2>&1 || true

# Install dependencies
pip install --upgrade pip
pip install -r requirements.txt

# Make sure we're in the right directory (Render uses /opt/render/project/src)
cd /opt/render/project/src 2>/dev/null || cd "$(dirname "$0")"

# Run migrations if DATABASE_URL is set (Render injects it when DB is linked)
if [ -n "${DATABASE_URL:-}" ]; then
  echo "Running migrations..."
  $PYTHON manage.py migrate --no-input
  echo "Migrations applied."
else
  echo "⚠️  DATABASE_URL not set during build; skipping migrate. Migrations run via preDeployCommand and start.sh on Render."
fi

# Collect static files (required for admin CSS/JS on Render)
echo "Collecting static files..."
$PYTHON manage.py collectstatic --noinput
echo "Static files collected."
