#!/usr/bin/env bash
set -euo pipefail

REGISTRY_ROOT="${FN_REGISTRY_ROOT:-$(cd "$(dirname "$0")/../../.." && pwd)}"
CPP_ROOT="$REGISTRY_ROOT/cpp"
BUILD_DIR="$CPP_ROOT/build/windows"
TOOLCHAIN="$CPP_ROOT/toolchains/mingw-w64.cmake"
TARGET="${1:-}"

# Check mingw is available
if ! command -v x86_64-w64-mingw32-g++ &>/dev/null; then
    echo "[build_cpp_windows] Error: mingw-w64 not found. Install with: sudo apt install mingw-w64"
    exit 1
fi

# Configure if needed
if [ ! -f "$BUILD_DIR/CMakeCache.txt" ]; then
    echo "[build_cpp_windows] Configuring cmake with mingw-w64 toolchain..."
    cmake -B "$BUILD_DIR" -S "$CPP_ROOT" -DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN"
fi

# Build
if [ -n "$TARGET" ]; then
    echo "[build_cpp_windows] Cross-compiling target: $TARGET"
    cmake --build "$BUILD_DIR" --target "$TARGET" -- -j"$(nproc)"
else
    echo "[build_cpp_windows] Cross-compiling all targets..."
    cmake --build "$BUILD_DIR" -- -j"$(nproc)"
fi

echo "[build_cpp_windows] Done. Windows binaries in $BUILD_DIR"
if [ -n "$TARGET" ]; then
    file "$BUILD_DIR"/**/"$TARGET".exe 2>/dev/null || file "$BUILD_DIR/$TARGET".exe 2>/dev/null || true
fi
