#!/usr/bin/env bash
# build_cpp_windows — Cross-compila apps C++ del registry para Windows con
# mingw-w64. Configura el build dir cpp/build/windows/ con la toolchain la
# primera vez y construye el target indicado (o todos).
#
# Uso (funcion via source):
#     source bash/functions/infra/build_cpp_windows.sh
#     build_cpp_windows my_app    # construye target especifico
#     build_cpp_windows           # construye todos
#
# Uso (script directo):
#     bash bash/functions/infra/build_cpp_windows.sh my_app

set -euo pipefail

build_cpp_windows() {
    local target="${1:-}"
    local registry_root="${FN_REGISTRY_ROOT:-}"
    if [ -z "$registry_root" ]; then
        local d="$PWD"
        while [ "$d" != "/" ]; do
            if [ -f "$d/registry.db" ] && [ -d "$d/cpp" ]; then
                registry_root="$d"; break
            fi
            d="$(dirname "$d")"
        done
    fi
    if [ -z "$registry_root" ]; then
        echo "[build_cpp_windows] No se localiza la raiz del registry. Exporta FN_REGISTRY_ROOT." >&2
        return 2
    fi
    local cpp_root="$registry_root/cpp"
    local build_dir="${BUILD_WIN:-$cpp_root/build/windows}"
    local toolchain="$cpp_root/toolchains/mingw-w64.cmake"

    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" >&2
        return 1
    fi

    if [ ! -f "$build_dir/CMakeCache.txt" ]; then
        echo "[build_cpp_windows] Configuring cmake with mingw-w64 toolchain..." >&2
        cmake -B "$build_dir" -S "$cpp_root" -DCMAKE_TOOLCHAIN_FILE="$toolchain"
    else
        # Re-run cmake to pick up new add_subdirectory entries cuando se anade
        # una app nueva al CMakeLists.txt (no rompe builds incrementales).
        cmake "$build_dir" >/dev/null
    fi

    if [ -n "$target" ]; then
        echo "[build_cpp_windows] Cross-compiling target: $target" >&2
        cmake --build "$build_dir" --target "$target" -- -j"$(nproc)"
    else
        echo "[build_cpp_windows] Cross-compiling all targets..." >&2
        cmake --build "$build_dir" -- -j"$(nproc)"
    fi

    echo "[build_cpp_windows] Done. Windows binaries in $build_dir" >&2
}

# Invocacion directa como script (compatibilidad).
if [ "${BASH_SOURCE[0]:-}" = "${0:-}" ] && [ -n "${BASH_SOURCE[0]:-}" ]; then
    build_cpp_windows "$@"
fi
