#!/bin/bash

###############################################################################
#
#  AdHub Legacy SDK - Build Bundle Script
#
#  Script per generare i bundle minificati dell'SDK Legacy
#
#  Usage:
#    ./build-bundle.sh                    # Build normale (dev + prod)
#    ./build-bundle.sh --prod-only        # Solo production
#    ./build-bundle.sh --dev-only         # Solo development
#    ./build-bundle.sh --clean            # Pulisce dist/ prima del build
#
#  Output:
#    dist/sdk.js         - Development bundle (non minificato)
#    dist/sdk.min.js     - Production bundle (minificato)
#
###############################################################################

set -e  # Exit on error

# Colori per output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Banner
echo -e "${CYAN}"
echo "╔════════════════════════════════════════════════════════════╗"
echo "║                                                            ║"
echo "║          AdHub Legacy SDK - Build Script                  ║"
echo "║                                                            ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# Directory di progetto
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# Verifica node_modules
if [ ! -d "node_modules" ]; then
    echo -e "${YELLOW}⚠️  node_modules non trovato, eseguo npm install...${NC}"
    npm install
fi

# Parse argomenti
BUILD_DEV=true
BUILD_PROD=true
CLEAN=false

for arg in "$@"; do
    case $arg in
        --prod-only)
            BUILD_DEV=false
            BUILD_PROD=true
            ;;
        --dev-only)
            BUILD_DEV=true
            BUILD_PROD=false
            ;;
        --clean)
            CLEAN=true
            ;;
        --help|-h)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --prod-only     Build solo production bundle (minificato)"
            echo "  --dev-only      Build solo development bundle"
            echo "  --clean         Pulisce dist/ prima del build"
            echo "  --help, -h      Mostra questo help"
            echo ""
            exit 0
            ;;
        *)
            echo -e "${RED}❌ Opzione sconosciuta: $arg${NC}"
            echo "Usa --help per vedere le opzioni disponibili"
            exit 1
            ;;
    esac
done

# Clean se richiesto
if [ "$CLEAN" = true ]; then
    echo -e "${YELLOW}🗑️  Pulizia directory dist/...${NC}"
    rm -rf dist/*.js
    echo -e "${GREEN}✅ Directory pulita${NC}"
fi

# Timestamp inizio
START_TIME=$(date +%s)

# Build development
if [ "$BUILD_DEV" = true ]; then
    echo -e "${BLUE}📦 Building DEVELOPMENT bundle...${NC}"
    npm run build:dev

    if [ -f "dist/sdk.js" ]; then
        SIZE=$(du -h dist/sdk.js | cut -f1)
        echo -e "${GREEN}✅ Development build completato (${SIZE})${NC}"
    else
        echo -e "${RED}❌ Errore build development${NC}"
        exit 1
    fi
fi

# Build production
if [ "$BUILD_PROD" = true ]; then
    echo -e "${BLUE}📦 Building PRODUCTION bundle...${NC}"
    npm run build:prod

    if [ -f "dist/sdk.min.js" ]; then
        SIZE=$(du -h dist/sdk.min.js | cut -f1)
        echo -e "${GREEN}✅ Production build completato (${SIZE})${NC}"
    else
        echo -e "${RED}❌ Errore build production${NC}"
        exit 1
    fi
fi

# Timestamp fine
END_TIME=$(date +%s)
DURATION=$((END_TIME - START_TIME))

# Mostra statistiche finali
echo ""
echo -e "${CYAN}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║                    BUILD SUMMARY                           ║${NC}"
echo -e "${CYAN}╚════════════════════════════════════════════════════════════╝${NC}"
echo ""

if [ -f "dist/sdk.js" ]; then
    DEV_SIZE=$(du -h dist/sdk.js | cut -f1)
    echo -e "  ${GREEN}✅${NC} Development: ${BLUE}dist/sdk.js${NC} (${DEV_SIZE})"
fi

if [ -f "dist/sdk.min.js" ]; then
    PROD_SIZE=$(du -h dist/sdk.min.js | cut -f1)
    echo -e "  ${GREEN}✅${NC} Production:  ${BLUE}dist/sdk.min.js${NC} (${PROD_SIZE})"

    # Calcola percentuale riduzione
    if [ -f "dist/sdk.js" ]; then
        DEV_BYTES=$(stat -f%z dist/sdk.js 2>/dev/null || stat -c%s dist/sdk.js)
        PROD_BYTES=$(stat -f%z dist/sdk.min.js 2>/dev/null || stat -c%s dist/sdk.min.js)
        REDUCTION=$(echo "scale=2; (1 - $PROD_BYTES / $DEV_BYTES) * 100" | bc)
        echo -e "  ${CYAN}📊${NC} Compressione: ${YELLOW}${REDUCTION}%${NC}"
    fi
fi

echo ""
echo -e "  ${CYAN}⏱️${NC}  Tempo build: ${YELLOW}${DURATION}s${NC}"
echo ""

# Verifica file output
echo -e "${CYAN}📋 File generati:${NC}"
ls -lh dist/*.js 2>/dev/null | awk '{print "  " $9 " (" $5 ")"}'

echo ""
echo -e "${GREEN}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║                    ✅ BUILD SUCCESS                        ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════════════════╝${NC}"
echo ""

# Mostra prossimi step
echo -e "${YELLOW}📌 Prossimi step:${NC}"
echo ""
echo -e "  ${CYAN}1.${NC} Test locale:"
echo -e "     ${BLUE}open examples/test-multiple-scripts.html${NC}"
echo ""
echo -e "  ${CYAN}2.${NC} Deploy su static.4wnetwork.com:"
echo -e "     ${BLUE}cp dist/sdk.min.js /var/www/html/static.4wnetwork.com/js/sdk.min.js${NC}"
echo ""
echo -e "  ${CYAN}3.${NC} Test live:"
echo -e "     ${BLUE}Aprire https://www.tusciaweb.eu e verificare console${NC}"
echo ""
