#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."

echo "Starting CapaKraken..."

# 1. Start Docker services
echo "  Starting PostgreSQL + Redis..."
docker compose up -d postgres redis
sleep 2

# 2. Wait for PostgreSQL to be healthy
echo "  Waiting for PostgreSQL..."
for i in {1..30}; do
  if docker compose exec -T postgres pg_isready -U capakraken -d capakraken -q 2>/dev/null; then
    break
  fi
  sleep 1
done

# 3. Start the web app in Docker for a stable lifecycle
echo "  Starting app container on port 3100..."
docker compose --profile full up -d app

# 4. Wait for server to be ready
# Allow up to 90s: prisma generate + migrate deploy + next dev compilation
echo "  Waiting for server (up to 90s)..."
for i in {1..90}; do
  if curl -sf http://localhost:3100/api/health > /dev/null 2>&1; then
    echo ""
    echo "CapaKraken is running!"
    curl -s http://localhost:3100/api/ready | python3 -m json.tool 2>/dev/null || curl -s http://localhost:3100/api/ready
    echo ""
    echo "  URL: http://localhost:3100"
    echo "  Logs: docker logs -f capakraken-app-1"
    exit 0
  fi
  # Print progress every 10s
  if (( i % 10 == 0 )); then
    echo "  Still waiting... (${i}s)"
  fi
  sleep 1
done

echo "ERROR: Server failed to start within 90 seconds"
echo "Check logs: docker logs --tail 100 capakraken-app-1"
exit 1
