#!/bin/bash
set -e
export PYTHONDONTWRITEBYTECODE=1
export PYTHONPYCACHEPREFIX=/dev/null

echo "==> Attendo il database..."
until python -c "
import asyncio
import asyncpg
import os

async def check():
    url = os.environ.get('DATABASE_URL', '').replace('postgresql+asyncpg://', '')
    parts = url.split('@')
    creds = parts[0].split(':')
    host_db = parts[1].split('/')
    await asyncpg.connect(
        user=creds[0], password=creds[1],
        host=host_db[0].split(':')[0],
        port=int(host_db[0].split(':')[1]) if ':' in host_db[0] else 5432,
        database=host_db[1]
    )

asyncio.run(check())
" 2>/dev/null; do
  echo "   DB non pronto, attendo..."
  sleep 2
done

echo "==> Eseguo migrazioni Alembic..."
alembic upgrade head

echo "==> Eseguo seed utenti demo..."
python -m app.services.seed 2>/dev/null || true

echo "==> Avvio server..."
exec uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
