#!/bin/bash
set -e

echo ""
echo "=========================================="
echo "  DWA AI Adoption Tracker - Setup"
echo "=========================================="
echo ""

# ---- Check Docker ----
if ! command -v docker &> /dev/null; then
    echo "Docker is not installed."
    echo ""
    echo "Install Docker Desktop from:"
    echo "  https://www.docker.com/products/docker-desktop/"
    echo ""
    echo "After installing, open Docker Desktop and wait for it to start,"
    echo "then run this script again."
    exit 1
fi

if ! docker info &> /dev/null 2>&1; then
    echo "Docker is installed but not running."
    echo ""
    echo "Open Docker Desktop and wait for it to start,"
    echo "then run this script again."
    exit 1
fi

echo "Docker is ready."
echo ""

# ---- Build and start ----
echo "Building and starting all services..."
echo "(This takes 2-3 minutes on first run)"
echo ""

docker compose up --build -d

echo ""
echo "Waiting for services to be ready..."
sleep 10

# ---- Check health ----
echo ""
echo "Checking services..."

for i in {1..30}; do
    if curl -sf http://localhost:8003/health > /dev/null 2>&1; then
        echo "Backend is ready."
        break
    fi
    if [ $i -eq 30 ]; then
        echo "Backend is taking a while. Check: docker compose logs backend"
    fi
    sleep 2
done

echo ""
echo "=========================================="
echo "  All set!"
echo "=========================================="
echo ""
echo "  Frontend:  http://localhost:3700"
echo "  Backend:   http://localhost:8003"
echo "  API Docs:  http://localhost:8003/docs"
echo ""
echo "  Login:     sara.al-mansoori@dwa.ae"
echo "  Password:  demo123"
echo ""
echo "  To stop:   docker compose down"
echo "  To start:  docker compose up -d"
echo "  Logs:      docker compose logs -f"
echo ""
