#!/bin/sh
# Runs once per container start, for both the backend and worker services (they share
# this image). Migrations are idempotent (alembic no-ops if already at head), so it's
# safe for both services to run this — whichever starts first applies them.
set -e

echo "Waiting for the database..."
python3 -c "
import sys
import time
from sqlalchemy import create_engine, text
from app.core.config import get_settings

url = get_settings().database_url
for attempt in range(30):
    try:
        create_engine(url).connect().close()
        sys.exit(0)
    except Exception as exc:
        print(f'  attempt {attempt + 1}/30: {exc}')
        time.sleep(2)
sys.exit('Database never became reachable')
"

echo "Applying database migrations..."
alembic upgrade head

echo "Starting: $*"
exec "$@"
