#!/bin/bash

###############################################################################
# AdHub - Build Site Bundles from Portal API
#
# Genera bundle per ogni sito scaricando la config dal Portal API.
# Questo è il nuovo approccio (Option B) dove la config viene dal DB.
#
# Usage:
#   ./build-sites-from-api.sh                    # Build tutti i siti
#   ./build-sites-from-api.sh zonanerd.com       # Build singolo sito
#   ./build-sites-from-api.sh --deploy           # Build + deploy CDN
#
# Output:
#   dist/{site}/adhub-{site}.js          (bundle esteso)
#   dist/{site}/adhub-{site}.min.js      (bundle minificato)
###############################################################################

set -e

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

# Directories
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
DIST_DIR="$ROOT_DIR/dist"

# API Configuration
API_URL="https://portal.adhubmedia.com/api/loader"

# CDN Configuration
CDN_HOST="Aptica-Docker2-116.203.172.135"
CDN_PATH="/opt/www/lib.adhubmedia.com/dist"

# Parse arguments
DEPLOY=false
SINGLE_SITE=""

for arg in "$@"; do
    case $arg in
        --deploy)
            DEPLOY=true
            shift
            ;;
        *)
            SINGLE_SITE="$arg"
            shift
            ;;
    esac
done

# Check for terser
check_terser() {
    if [ -f "$ROOT_DIR/node_modules/.bin/terser" ]; then
        TERSER_CMD="$ROOT_DIR/node_modules/.bin/terser"
        return 0
    elif command -v terser &> /dev/null; then
        TERSER_CMD="terser"
        return 0
    else
        echo -e "${RED}❌ Terser not found. Run 'npm install' first.${NC}"
        exit 1
    fi
}

# Build single site from API
build_site() {
    local site="$1"
    local site_dir="$DIST_DIR/$site"
    local site_clean=$(echo "$site" | sed 's/\./-/g')

    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}🔨 Building: $site${NC}"

    # Create output directory
    mkdir -p "$site_dir"

    # Fetch bootstrap script from API
    local bootstrap_url="$API_URL/bootstrap/$site"
    local output_js="$site_dir/adhub-$site.js"
    local output_min="$site_dir/adhub-$site.min.js"

    echo -e "  📥 Fetching bootstrap from API..."

    # Download bootstrap
    local http_code=$(curl -s -w "%{http_code}" -o "$output_js" "$bootstrap_url")

    if [ "$http_code" != "200" ]; then
        echo -e "${YELLOW}  ⚠️  Site not found in DB (HTTP $http_code) - skipping${NC}"
        rm -f "$output_js"
        return 1
    fi

    # Check if valid JS
    if ! grep -q "AdHubGAMConfig" "$output_js"; then
        echo -e "${YELLOW}  ⚠️  Invalid bootstrap response - skipping${NC}"
        rm -f "$output_js"
        return 1
    fi

    local js_size=$(wc -c < "$output_js")
    echo -e "  ✅ Bootstrap downloaded (${js_size} bytes)"

    # Minify
    echo -e "  🗜️  Minifying..."
    $TERSER_CMD "$output_js" \
        --compress drop_console=false,passes=2 \
        --mangle \
        --output "$output_min" 2>/dev/null

    local min_size=$(wc -c < "$output_min")
    local ratio=$((100 - (min_size * 100 / js_size)))

    echo -e "  ✅ Minified: ${min_size} bytes (${ratio}% smaller)"

    return 0
}

# Get list of all sites from API
get_all_sites() {
    # Fetch sites list from portal API
    # First try the internal API endpoint
    local sites=$(curl -s "$API_URL/../internal/sites" 2>/dev/null | grep -oP '"domain"\s*:\s*"\K[^"]+' | sort -u)

    if [ -z "$sites" ]; then
        # Fallback: use known sites from dist directory on CDN
        sites=$(ssh -o ConnectTimeout=5 $CDN_HOST "ls -1 $CDN_PATH 2>/dev/null" | grep -v core | grep '\.' | head -200)
    fi

    echo "$sites"
}

# Deploy to CDN
deploy_to_cdn() {
    local site="$1"
    local site_dir="$DIST_DIR/$site"

    if [ ! -d "$site_dir" ]; then
        return 1
    fi

    echo -e "  🚀 Deploying to CDN..."
    rsync -az "$site_dir/" "$CDN_HOST:$CDN_PATH/$site/" 2>/dev/null

    if [ $? -eq 0 ]; then
        echo -e "  ✅ Deployed to CDN"
    else
        echo -e "${YELLOW}  ⚠️  CDN deploy failed${NC}"
    fi
}

# Main
print_banner() {
    echo ""
    echo -e "${BLUE}╔══════════════════════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║  AdHub - Build Sites from API (Option B)                ║${NC}"
    echo -e "${BLUE}╚══════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

print_banner
check_terser

if [ -n "$SINGLE_SITE" ]; then
    # Build single site
    build_site "$SINGLE_SITE"
    if [ "$DEPLOY" = true ] && [ $? -eq 0 ]; then
        deploy_to_cdn "$SINGLE_SITE"
    fi
else
    # Build all sites
    echo -e "${BLUE}📋 Fetching site list from API...${NC}"
    sites=$(get_all_sites)

    if [ -z "$sites" ]; then
        echo -e "${RED}❌ No sites found${NC}"
        exit 1
    fi

    total=$(echo "$sites" | wc -l)
    echo -e "${GREEN}Found $total sites${NC}"
    echo ""

    success=0
    failed=0

    for site in $sites; do
        if build_site "$site"; then
            ((success++))
            if [ "$DEPLOY" = true ]; then
                deploy_to_cdn "$site"
            fi
        else
            ((failed++))
        fi
    done

    echo ""
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}✅ Build complete: $success success, $failed skipped${NC}"
fi

echo ""
echo -e "${GREEN}✨ Done!${NC}"
