#!/bin/bash -eu

julia_version=""
_yes_to_all=false

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --version)
            if [[ $# -lt 2 ]]; then
                echo "Error: --version requires a version argument"
                exit 1
            fi
            julia_version="$2"
            shift 2
            ;;
        -y|--yes)
            _yes_to_all=true
            shift
            ;;
        *)
            echo "Invalid parameter! Use:"
            echo "./create_sys_image"
            echo "or"
            echo "./create_sys_image --version 1.x"
            echo "or"
            echo "./create_sys_image -y"
            echo "or"
            echo "./create_sys_image --yes"
            exit 1
            ;;
    esac
done

if [[ -n "$julia_version" ]]; then
    JULIA_CMD="julia +$julia_version"
else
    JULIA_CMD="julia"
fi

if [[ $(basename $(pwd)) == "bin" ]]; then
    cd ..
fi

mkdir -p output

export MPLBACKEND=agg
export JULIA_PKG_SERVER_REGISTRY_PREFERENCE="eager"

if ! command -v juliaup &> /dev/null; then
    echo "Juliaup not found. Please run: ./install"
    exit 1
fi

# if julia is not installed, install Julia 1.11
if ! command -v julia &> /dev/null; then
    echo "Julia not found. Please run: ./install"
    exit 1
fi

. ./bin/setup_env

julia_version=$($JULIA_CMD --version | awk '{print($3)}')
julia_major=${julia_version:0:3}
if [[ $julia_major == "1.1" ]]; then
    julia_major=${julia_version:0:4} 
fi

# if the current julia version is older than 1.10, exit
if [[ $julia_major == "1.11" ]] || [[ $julia_major == "1.12" ]]; then
    echo "Supported Julia version found!"
else
    echo "The current Julia version is not supported, installing Julia 1.11!"
    juliaup add 1.11
    juliaup default 1.11
fi

PYTHON_PATH=$(which python3)
if [ -x "$PYTHON_PATH" ]; then
    echo "Python is found at $PYTHON_PATH"
    if $PYTHON_PATH -c "import matplotlib" &> /dev/null; then
        echo "Matplotlib found. Using existing installation."
        export PYTHON=$PYTHON_PATH
    else
        echo "Matplotlib is not found."
                if [[ $_yes_to_all == true ]]; then
                        echo "Installing matplotlib with Conda..."
                        export PYTHON=""
                else
                        read -p "Do you want to install matplotlib with Conda? (y/n): " choice
                        case "$choice" in 
                            y|Y ) 
                                export PYTHON=""
                                ;;
                            n|N ) 
                                echo "Exiting without installing matplotlib."
                                exit 1
                                ;;
                            * ) 
                                echo "Invalid choice. Exiting."
                                exit 1
                                ;;
                        esac
                fi
    fi
else
    echo "Python is not found."
    exit 1
fi

# create a logfile for the sysimage creation process
./bin/batch_pilot hydra20_600

# Check memory and limit threads if needed
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" ]]; then
    # Windows: use wmic or PowerShell
    echo "Checking system memory on Windows..."
    totalmem=$(powershell.exe -Command "(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1MB" 2>/dev/null | awk '{printf "%i", $1}')
    if [[ -z "$totalmem" || $totalmem -lt 27000 ]]; then
        echo "Warning: Less than 27GB of memory detected on Windows. Using only one thread for sysimage compilation."
        export JULIA_IMAGE_THREADS=1
    fi
elif [[ "$OSTYPE" == darwin* ]]; then
    # macOS: use sysctl
    echo "Checking system memory on macOS..."
    totalmem=$(sysctl -n hw.memsize 2>/dev/null | awk '{printf "%i", $1 / 1000000}')
    if [[ -z "$totalmem" || $totalmem -lt 27000 ]]; then
        echo "Warning: Less than 27GB of memory detected on macOS. Using only one thread for sysimage compilation."
        export JULIA_IMAGE_THREADS=1
    fi
else
    # Linux: use /proc/meminfo
    totalmem=$(grep MemTotal /proc/meminfo | awk '{printf "%i", $2 / 1024}')
    if [[ $totalmem -lt 26674 ]]; then
        echo "Warning: Less than 27GB of memory detected. Using only one thread for sysimage compilation."
        export JULIA_IMAGE_THREADS=1
    fi
fi

if [ -d .git ] || git rev-parse --git-dir > /dev/null 2>&1 ; then
    branch=$(git rev-parse --abbrev-ref HEAD | sed 's/\//-/g')
else
    branch=""
fi
if test -f "kps-image-${julia_major}-${branch}.so"; then
    mv bin/kps-image-${julia_major}-${branch}.so kps-image-${julia_major}-${branch}.so.bak
fi

$JULIA_CMD --startup-file=no --project -e "using Pkg; Pkg.instantiate();"
$JULIA_CMD --startup-file=no --project=test --heap-size-hint=8000M -e "include(\"./test/create_sys_image.jl\")"

SOFILE="bin/kps-image-${julia_major}.so"
if test -f $SOFILE; then
    mv $SOFILE $SOFILE.bak
fi
mv kps-image_tmp.so $SOFILE
$JULIA_CMD --startup-file=no  --project -e "using Pkg; Pkg.precompile(); Pkg.resolve()"
$JULIA_CMD --project -J bin/kps-image-${julia_major}-${branch}.so -e "using KiteUtils, KiteControllers"
$JULIA_CMD --project=test -J bin/kps-image-${julia_major}-${branch}.so -e "using ControlPlots, NativeFileDialog"
$JULIA_CMD --project -J bin/kps-image-${julia_major}-${branch}.so -e "using Pkg; Pkg.instantiate()"
$JULIA_CMD --project=examples -J bin/kps-image-${julia_major}-${branch}.so -e "using NOMAD, KiteViewers, Pkg; Pkg.instantiate(); Pkg.precompile()"

# On Linux, suppress known-harmless Julia extension loading warnings (e.g. DistributionsTestExt).
# The error spans multiple lines (┌ Error: ... │ ... └ @ Base), so use sed range deletion.
if [[ "$(uname -s)" == "Linux" ]]; then
    exec 2> >(sed '/Error during loading of extension FilePathsURIsExt of FilePaths/,/^└/d' >&2)
fi
$JULIA_CMD --project=docs -J bin/kps-image-${julia_major}-${branch}.so -e "using LiveServer, Documenter, Pkg; Pkg.instantiate()"