#!/bin/bash
# Update all Dockerfiles to use optimized requirements

set -e

echo "🔧 Updating Dockerfiles to use optimized requirements..."

# List of all services
SERVICES=(
    "svc_extract"
    "svc_kg"
    "svc_rag_retriever"
    "svc_rag_indexer"
    "svc_forms"
    "svc_hmrc"
    "svc_ocr"
    "svc_rpa"
    "svc_normalize_map"
    "svc_reason"
    "svc_firm_connectors"
    "svc_coverage"
)

for service in "${SERVICES[@]}"; do
    dockerfile="apps/$service/Dockerfile"
    
    if [ ! -f "$dockerfile" ]; then
        echo "⚠️  Dockerfile not found: $dockerfile"
        continue
    fi
    
    echo "📝 Updating $service..."
    
    # Create backup
    cp "$dockerfile" "$dockerfile.bak"
    
    # Update the requirements copy and install lines
    sed -i.tmp \
        -e 's|COPY libs/requirements\.txt /tmp/libs-requirements\.txt|COPY libs/requirements-base.txt /tmp/libs-requirements.txt|g' \
        -e 's|COPY apps/.*/requirements\.txt /tmp/requirements\.txt|COPY apps/'"$service"'/requirements.txt /tmp/requirements.txt|g' \
        -e 's|RUN pip install --no-cache-dir -r /tmp/requirements\.txt -r /tmp/libs-requirements\.txt|RUN pip install --no-cache-dir --upgrade pip \&\& \\\n    pip install --no-cache-dir -r /tmp/libs-requirements.txt -r /tmp/requirements.txt|g' \
        "$dockerfile"
    
    # Remove temp file
    rm -f "$dockerfile.tmp"
    
    echo "✅ Updated $service"
done

echo ""
echo "✅ All Dockerfiles updated!"
echo ""
echo "📋 Next steps:"
echo "1. Review changes: git diff apps/*/Dockerfile"
echo "2. Clean Docker cache: docker system prune -a"
echo "3. Rebuild images: ./scripts/build-and-push-images.sh gitea.harkon.co.uk v1.0.1 blue"
echo "4. Verify sizes: docker images | grep gitea.harkon.co.uk"

