#!/bin/bash
set -e

echo "======================================"
echo "Codeflash Unified Container Builder"
echo "======================================"
echo ""

# Get the repository root (2 levels up from this script)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

cd "$REPO_ROOT"

echo "Repository root: $REPO_ROOT"
echo ""

# Check if we should skip individual builds (for faster rebuilds)
SKIP_SERVICE_BUILDS=${SKIP_SERVICE_BUILDS:-false}

if [ "$SKIP_SERVICE_BUILDS" = "false" ]; then
  echo "Step 1/3: Building aiservice image..."
  echo "--------------------------------------"
  docker build -f deployment/onprem-simple/Dockerfile.aiservice -t codeflash/aiservice:latest .
  echo "✓ aiservice image built successfully"
  echo ""

  echo "Step 2/3: Building cf-api image..."
  echo "--------------------------------------"
  docker build -f deployment/onprem-simple/Dockerfile.cfapi -t codeflash/cf-api:latest .
  echo "✓ cf-api image built successfully"
  echo ""
else
  echo "Skipping individual service builds (SKIP_SERVICE_BUILDS=true)"
  echo "Using existing codeflash/aiservice:latest and codeflash/cf-api:latest"
  echo ""
fi

echo "Step 3/3: Building unified container..."
echo "--------------------------------------"
docker build -f deployment/onprem-simple/Dockerfile.unified-simple -t codeflash/unified:latest .
echo "✓ unified container built successfully"
echo ""

echo "======================================"
echo "✓ Build Complete!"
echo "======================================"
echo ""
echo "Image: codeflash/unified:latest"
echo ""
echo "To run the container, use:"
echo "  docker run -d --name codeflash \\"
echo "    --env-file .env \\"
echo "    -p 5432:5432 \\"
echo "    -p 8000:8000 \\"
echo "    -p 3001:3001 \\"
echo "    -v codeflash-data:/var/lib/postgresql/data \\"
echo "    codeflash/unified:latest"
echo ""
echo "Or see deployment/onprem-simple/README.md for detailed instructions."
echo ""