#!/bin/bash
# Voxis Diagnostic Build Protocol (ARM64 + LibreSSL)
set -e # Exit immediately if any command fails

# --- 1. PATH RECONNAISSANCE ---
# Resolve absolute paths to stop relative path madness
BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$BASE_DIR" # Ensure we are in core/nip/

VENDOR="$(realpath ../../core/nexus/vendor)"
ZSTD_PATH="$VENDOR/zstd-1.5.5/lib"
LIBRE_PATH="$VENDOR/libressl-3.8.2"

LIBRE_SSL_LIB="$LIBRE_PATH/ssl/.libs"
LIBRE_CRYPTO_LIB="$LIBRE_PATH/crypto/.libs"
LIBRE_TLS_LIB="$LIBRE_PATH/tls/.libs"

OUTPUT_DIR="$BASE_DIR/build/arm64"
TARGET_BIN="$OUTPUT_DIR/nip"

echo "🔎 [DIAGNOSTIC] Path Verification:"
echo "   Base:   $BASE_DIR"
echo "   Vendor: $VENDOR"
echo "   Output: $OUTPUT_DIR"

# Check Critical Assets
for lib in "$ZSTD_PATH/libzstd.a" "$LIBRE_SSL_LIB/libssl.a" "$LIBRE_CRYPTO_LIB/libcrypto.a"; do
    if [ ! -f "$lib" ]; then
        echo "❌ CRITICAL FAILURE: Missing Asset -> $lib"
        echo "   Did you run 'make' inside the library directories?"
        exit 1
    fi
done
echo "✅ All Static Libraries Found."

mkdir -p "$OUTPUT_DIR"

# --- 2. THE COMPILATION (FORCE MODE) ---
echo "🔨 [FORGE] Starting Compilation..."

# Put wrapper in PATH to filter x86 flags
export PATH="/tmp/gcc-wrapper-bin:$PATH"

# -f          : Force rebuild (ignore cache)
# --listCmd   : SHOW ME THE LINKER COMMAND

nim c -f --listCmd \
      --skipProjCfg \
      --nimcache:/tmp/nip-arm64-cache \
      -d:release -d:ssl -d:openssl \
      -d:nimcrypto_disable_neon \
      -d:nimcrypto_no_asm \
      --cpu:arm64 --os:linux \
      --cc:gcc \
      --gcc.exe:aarch64-linux-gnu-gcc \
      --gcc.linkerexe:aarch64-linux-gnu-gcc \
      --dynlibOverride:ssl --dynlibOverride:crypto \
      --passC:"-I$ZSTD_PATH -I$LIBRE_PATH/include" \
      --passL:"-L$ZSTD_PATH -L$LIBRE_SSL_LIB -L$LIBRE_CRYPTO_LIB -L$LIBRE_TLS_LIB" \
      --passL:"-static -lssl -lcrypto -ltls -lzstd -lpthread -ldl -lm -lresolv" \
      --opt:size \
      --mm:orc \
      --threads:on \
      -o:"$TARGET_BIN" \
      src/nip.nim

# --- 3. POST-MORTEM ---
echo "---------------------------------------------------"
if [ -f "$TARGET_BIN" ]; then
    echo "✅ SUCCESS: Binary located at:"
    ls -l "$TARGET_BIN"
    file "$TARGET_BIN"
else
    echo "❌ FAILURE: Output file missing at $TARGET_BIN"
    echo "🔎 Searching for 'nip' binaries in the tree..."
    find . -type f -name nip -exec ls -l {} +
fi
