#!/bin/bash

###############################################################################
# AdHub - Build Monolithic Site Bundle
#
# Generates a single-file bundle containing:
# 1. Site-specific config (from portal API bootstrap, without core loader)
# 2. All core modules (adhub-core.js)
#
# This avoids the extra network round-trip of the modular loader while
# still using the latest configs from the portal database.
#
# Usage:
#   ./build-monolithic-site.sh <domain>
#   ./build-monolithic-site.sh --deploy <domain>
#   ./build-monolithic-site.sh --deploy-all   # All sites (EXCLUDES sites in SKIP_LIST)
#
###############################################################################

set -e

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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LIB_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
DIST_DIR="$LIB_DIR/dist"
# Use noloader variant: no AdHubLoader module = no polling/timeouts
# Modules use direct fallback path (check global objects) which is faster
CORE_JS="$DIST_DIR/core/adhub-core-noloader.js"
CORE_MIN_JS="$DIST_DIR/core/adhub-core-noloader.min.js"

API_BASE="${PORTAL_API_URL:-http://localhost:3000}"

CDN_HOST="Aptica-Docker2-116.203.172.135"
CDN_USER="root"
CDN_PATH="/opt/www/lib.adhubmedia.com/dist"

# Sites to skip (e.g. running monolithic from backup)
SKIP_LIST="${SKIP_SITES:-notizie.it}"

# Check for terser
if [ -f "$LIB_DIR/node_modules/.bin/terser" ]; then
    TERSER_CMD="$LIB_DIR/node_modules/.bin/terser"
elif command -v terser &> /dev/null; then
    TERSER_CMD="terser"
else
    echo -e "${RED}❌ Terser not found${NC}"
    exit 1
fi

# Check core bundle exists
if [ ! -f "$CORE_JS" ]; then
    echo -e "${RED}❌ Core bundle not found: $CORE_JS${NC}"
    echo -e "${YELLOW}Run build-core-bundle.sh first${NC}"
    exit 1
fi

extract_site_config() {
    local domain="$1"
    local output="$2"

    # Fetch bootstrap from API
    local bootstrap
    bootstrap=$(curl -sf "${API_BASE}/api/loader/bootstrap/${domain}" 2>/dev/null)

    if [ -z "$bootstrap" ]; then
        echo -e "${RED}  ❌ Failed to fetch config for: $domain${NC}"
        return 1
    fi

    # Extract only the config part (window.* assignments) - remove the core bundle loader
    # The bootstrap is an IIFE that sets window configs and then loads a <script> for the core.
    # We want: everything up to (but not including) the "// Load the combined core bundle" section.
    # Then we close the IIFE properly.

    # Strategy: use node to parse and extract config assignments
    node -e "
    const bootstrap = process.argv[1];

    // Find the config section end - before core bundle loading
    const loadMarker = bootstrap.indexOf('// Load the combined core bundle');
    const coreScriptMarker = bootstrap.indexOf(\"var coreScript = document.createElement('script')\");

    // Use whichever marker we find first
    let cutPoint = -1;
    if (loadMarker !== -1) cutPoint = loadMarker;
    if (coreScriptMarker !== -1 && (cutPoint === -1 || coreScriptMarker < cutPoint)) cutPoint = coreScriptMarker;

    if (cutPoint === -1) {
        // No core loader found - output the whole thing (might already be monolithic)
        process.stdout.write(bootstrap);
        process.exit(0);
    }

    // Get config section (from start to cut point)
    let configSection = bootstrap.substring(0, cutPoint);

    // Close the IIFE: add })();
    // But first check if it's already within an IIFE
    configSection = configSection.trimEnd();

    // Remove trailing IIFE wrapper - we'll re-wrap everything
    // Find the opening (function() { 'use strict';
    const iifeStart = configSection.indexOf(\"(function()\");
    if (iifeStart !== -1) {
        // Extract just the body (after first { and before we close)
        const bodyStart = configSection.indexOf('{', iifeStart) + 1;
        let body = configSection.substring(bodyStart);
        // Remove 'use strict'; if present
        body = body.replace(/^\\s*'use strict';?\\s*/, '');
        process.stdout.write(body);
    } else {
        process.stdout.write(configSection);
    }
    " "$bootstrap" > "$output"
}

build_monolithic() {
    local domain="$1"
    local site_dist="$DIST_DIR/$domain"
    mkdir -p "$site_dist"

    echo -e "${GREEN}🔨 Building monolithic for: ${YELLOW}${domain}${NC}"

    # Step 1: Extract site config from API
    local config_tmp=$(mktemp)
    if ! extract_site_config "$domain" "$config_tmp"; then
        rm -f "$config_tmp"
        return 1
    fi
    echo -e "  📥 Site config extracted"

    # Step 2: Concatenate into monolithic bundle
    local combined_tmp=$(mktemp)
    cat > "$combined_tmp" <<'HEADER'
(function() {
  'use strict';
HEADER

    # Add site config (domain guard + window.* assignments)
    cat "$config_tmp" >> "$combined_tmp"

    # Add separator
    echo "" >> "$combined_tmp"
    echo "// === CORE MODULES ===" >> "$combined_tmp"
    echo "" >> "$combined_tmp"

    # Add core modules (unminified for proper concatenation, will minify at end)
    cat "$CORE_JS" >> "$combined_tmp"

    # Close IIFE
    cat >> "$combined_tmp" <<'FOOTER'

})();
FOOTER

    # Step 3: Minify
    local output_js="$site_dist/adhub-${domain}.js"
    local output_min="$site_dist/adhub-${domain}.min.js"

    cp "$combined_tmp" "$output_js"

    $TERSER_CMD "$combined_tmp" \
        --compress passes=2,dead_code=true,drop_console=false \
        --mangle \
        --output "$output_min" 2>/dev/null

    local orig_size=$(wc -c < "$combined_tmp")
    local min_size=$(wc -c < "$output_min")
    echo -e "${GREEN}  ✓ Monolithic built: $output_min (${min_size} bytes, from ${orig_size})${NC}"

    # Cleanup
    rm -f "$config_tmp" "$combined_tmp"
}

deploy_to_cdn() {
    local domain="$1"
    local site_dist="$DIST_DIR/$domain"

    echo -e "${BLUE}  🚀 Deploying to CDN...${NC}"
    rsync -az --timeout=30 "$site_dist/" "${CDN_USER}@${CDN_HOST}:${CDN_PATH}/${domain}/"
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}  ✓ Deployed to CDN${NC}"
    else
        echo -e "${RED}  ❌ Deploy failed${NC}"
        return 1
    fi
}

build_and_deploy_all() {
    echo -e "${BLUE}📦 Building monolithic bundles for all sites...${NC}"
    echo -e "${YELLOW}⚠️  Skipping: ${SKIP_LIST}${NC}"
    echo ""

    local sites
    sites=$(curl -sf "${API_BASE}/api/loader/sites" 2>/dev/null | node -e "
        const data = require('fs').readFileSync(0,'utf8');
        JSON.parse(data).forEach(s => console.log(s));
    " 2>/dev/null)

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

    local total=$(echo "$sites" | wc -l)
    local success=0
    local skipped=0
    local failed=0

    for site in $sites; do
        # Check skip list
        if echo "$SKIP_LIST" | grep -qw "$site"; then
            echo -e "${YELLOW}⏭️  Skipping: $site${NC}"
            skipped=$((skipped + 1))
            continue
        fi

        if build_monolithic "$site"; then
            deploy_to_cdn "$site"
            success=$((success + 1))
        else
            failed=$((failed + 1))
        fi
    done

    echo ""
    echo -e "${GREEN}✅ Done: $success built+deployed, $skipped skipped, $failed failed (total: $total)${NC}"
}

# ============================================================================
# MAIN
# ============================================================================

echo ""
echo -e "${BLUE}╔══════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║  AdHub - Build Monolithic Site Bundle                   ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════╝${NC}"
echo ""

case "${1:-}" in
    --deploy-all)
        build_and_deploy_all
        ;;
    --deploy)
        if [ -z "${2:-}" ]; then
            echo -e "${RED}Error: Domain required${NC}"
            exit 1
        fi
        build_monolithic "$2"
        deploy_to_cdn "$2"
        ;;
    --help|-h)
        echo "Usage:"
        echo "  $0 <domain>              Build monolithic bundle"
        echo "  $0 --deploy <domain>     Build and deploy to CDN"
        echo "  $0 --deploy-all          Build+deploy all (skips SKIP_SITES)"
        echo ""
        echo "Environment:"
        echo "  PORTAL_API_URL    API base URL (default: http://localhost:3000)"
        echo "  SKIP_SITES        Space-separated domains to skip (default: notizie.it)"
        ;;
    "")
        echo -e "${RED}Error: Domain required${NC}"
        exit 1
        ;;
    *)
        build_monolithic "$1"
        ;;
esac

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