#!/bin/bash

set -euo pipefail

# Script to test maximum string length across Node versions

# Create a temporary directory for downloads
TMP_DIR=$(mktemp -d)
trap "rm -rf $TMP_DIR" EXIT

cd "$TMP_DIR"

# Function to test a Node version
test_node_version() {
    local version="$1"
    local node_bin="$TMP_DIR/node-${version}-linux-arm64/bin/node"
    local arch="arm64"
    
    # Check if we need to download this version
    if [ ! -f "$node_bin" ]; then
        echo "Downloading Node ${version}..." >&2
        
        # Try linux-arm64 first
        local url="https://nodejs.org/dist/${version}/node-${version}-linux-arm64.tar.gz"
        if curl -f -s -I "$url" > /dev/null 2>&1; then
            curl -s "$url" | tar xz
        else
            # Try linux-x64 as fallback
            echo "arm64 not available, trying x64..." >&2
            url="https://nodejs.org/dist/${version}/node-${version}-linux-x64.tar.gz"
            if curl -f -s -I "$url" > /dev/null 2>&1; then
                curl -s "$url" | tar xz
                node_bin="$TMP_DIR/node-${version}-linux-x64/bin/node"
                arch="x64"
            else
                echo "Skipping ${version} - not available" >&2
                return 1
            fi
        fi
    fi
    
    echo "Testing Node ${version}..." >&2
    
    # Run the binary search test
    # For very old versions, we may need to use var instead of let/const
    "$node_bin" --max-old-space-size=8192 -e '
        var low=0,high=4*1024*1024*1024,maxLen=0;
        while(low<=high){
            var mid=Math.floor((low+high)/2);
            try{
                var s=new Array(mid+1).join("x");
                maxLen=mid;
                low=mid+1
            }catch(e){
                high=mid-1
            }
        }
        console.log(JSON.stringify({
            maxLength:maxLen,
            v8:process.versions.v8,
            node:process.versions.node
        }))
    ' 2>/dev/null || echo '{"maxLength":0,"v8":"unknown","node":"'"${version#v}"'","error":"test failed"}'
}

# Generate list of versions to test
echo "[" > results.json
first=true

# Test versions from 8 to 25 (older versions fail due to platform/compatibility issues)
VERSIONS=()

# Get latest for each major version from 8 to 25
for major in {8..25}; do
    latest=$(curl -s https://nodejs.org/dist/ | \
        grep -oP "v${major}\.[0-9]+\.[0-9]+" | \
        sort -V | \
        tail -1 || true)
    
    if [ -n "$latest" ]; then
        VERSIONS+=("$latest")
    fi
done

# Test each version
for version in "${VERSIONS[@]}"; do
    if test_node_version "$version"; then
        if [ "$first" = true ]; then
            first=false
        else
            echo "," >> results.json
        fi
        test_node_version "$version" >> results.json
    fi
done

echo "" >> results.json
echo "]" >> results.json

cat results.json
