#!/bin/bash
# fast-build.sh - Ultra-fast local builds with smart caching
# Usage: ./scripts/fast-build.sh [service-name]

set -e

REGISTRY="registry.nxtgauge.com"
SERVICE=${1:-""}

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${BLUE}🚀 Nxtgauge Fast Build System${NC}"
echo "================================"

# If no service specified, detect changes
if [ -z "$SERVICE" ]; then
  echo "🔍 Detecting changed services..."
  
  CHANGED_FILES=$(git diff --name-only HEAD~1 HEAD 2>/dev/null || echo "")
  
  # Check if shared crates changed
  if echo "$CHANGED_FILES" | grep -q "^crates/"; then
    echo -e "${YELLOW}⚠️  Shared crates changed - need full rebuild${NC}"
    echo "Consider running: ./scripts/build-base-image.sh"
  fi
  
  # Find changed services
  for svc in gateway users companies job_seekers customers payments employees photographers makeup_artists tutors developers video_editors graphic_designers social_media_managers fitness_trainers catering_services ugc_content_creators cron; do
    svc_path=$(echo "$svc" | tr '_' '-')
    if echo "$CHANGED_FILES" | grep -q "^apps/${svc_path}/"; then
      echo -e "${GREEN}✅ $svc changed${NC}"
      SERVICE="$svc"
      break
    fi
  done
  
  if [ -z "$SERVICE" ]; then
    echo -e "${YELLOW}No services changed. Specify one:${NC}"
    echo "./scripts/fast-build.sh users"
    exit 0
  fi
  
  echo ""
  echo -e "${BLUE}Building: $SERVICE${NC}"
fi

# Check if base image exists
if ! docker image inspect ${REGISTRY}/nxtgauge-rust-base:latest &>/dev/null; then
  echo -e "${YELLOW}⚠️  Base image not found. Building dependencies...${NC}"
  echo "This will take 10-15 minutes (one-time setup)"
  ./scripts/build-base-image.sh
fi

# Use the fastest Dockerfile available
if [ -f "Dockerfile.superfast" ]; then
  DOCKERFILE="Dockerfile.superfast"
  echo -e "${BLUE}Using superfast build (cached dependencies)${NC}"
else
  DOCKERFILE="Dockerfile.fast"
  echo -e "${BLUE}Using fast build (cargo-chef)${NC}"
fi

echo ""
echo "🔨 Building ${SERVICE}..."

# Build with cache
docker build \
  --build-arg SERVICE_NAME=${SERVICE} \
  -f ${DOCKERFILE} \
  --cache-from ${REGISTRY}/nxtgauge-rust-${SERVICE}:cache \
  --cache-from ${REGISTRY}/nxtgauge-rust-${SERVICE}:latest \
  --build-arg BUILDKIT_INLINE_CACHE=1 \
  -t ${REGISTRY}/nxtgauge-rust-${SERVICE}:fast-build \
  .

# Show image size
SIZE=$(docker images --format "{{.Size}}" ${REGISTRY}/nxtgauge-rust-${SERVICE}:fast-build)
echo ""
echo -e "${GREEN}✅ Build complete!${NC}"
echo "   Service: ${SERVICE}"
echo "   Image: ${REGISTRY}/nxtgauge-rust-${SERVICE}:fast-build"
echo "   Size: ${SIZE}"

echo ""
echo -e "${BLUE}Push to registry:${NC}"
echo "  docker push ${REGISTRY}/nxtgauge-rust-${SERVICE}:fast-build"
echo ""
echo -e "${BLUE}Test locally:${NC}"
echo "  docker run -p 9100:9100 ${REGISTRY}/nxtgauge-rust-${SERVICE}:fast-build"
