#!/usr/bin/env bash
# Pipeline: compile_cpp_app — Resuelve la app, la cross-compila para Windows y despliega al escritorio.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INFRA_DIR="$SCRIPT_DIR/../infra"

source "$INFRA_DIR/resolve_cpp_app_dir.sh"
source "$INFRA_DIR/build_cpp_windows.sh"
source "$INFRA_DIR/deploy_cpp_exe_to_windows.sh"

compile_cpp_app() {
    local app_arg="${1:-}"

    # --- Paso 1: Resolver nombre y directorio de la app ---
    echo "[1/3] Resolviendo app..." >&2
    local resolved
    resolved=$(resolve_cpp_app_dir "$app_arg")
    local APP APP_DIR
    APP="$(echo "$resolved" | cut -f1)"
    APP_DIR="$(echo "$resolved" | cut -f2)"
    echo "  App: $APP" >&2
    echo "  Dir: $APP_DIR" >&2

    # --- Verificar que tiene CMakeLists.txt ---
    if [ ! -f "$APP_DIR/CMakeLists.txt" ]; then
        echo "ERROR: $APP_DIR/CMakeLists.txt no encontrado." >&2
        echo "La app '$APP' no esta registrada con CMake. Ver cpp_apps.md §5." >&2
        return 1
    fi

    # --- Paso 2: Cross-compilar para Windows ---
    echo "" >&2
    echo "[2/3] Compilando '$APP' para Windows (mingw-w64)..." >&2
    build_cpp_windows "$APP"

    # --- Paso 3: Desplegar al escritorio de Windows ---
    echo "" >&2
    echo "[3/3] Desplegando '$APP' al escritorio de Windows..." >&2
    deploy_cpp_exe_to_windows "$APP" "$APP_DIR"

    # --- Resumen final ---
    local root="${FN_REGISTRY_ROOT:-/home/lucas/fn_registry}"
    local build_win="${BUILD_WIN:-$root/cpp/build/windows}"
    local win_desktop_apps="${WIN_DESKTOP_APPS:-/mnt/c/Users/lucas/Desktop/apps}"
    local final_exe="$win_desktop_apps/$APP/$APP.exe"

    echo "" >&2
    if [ -f "$final_exe" ]; then
        echo "===== compile_cpp_app: OK =====" >&2
        ls -lh "$final_exe" >&2
    else
        echo "WARN: no se encuentra $final_exe" >&2
    fi
}

compile_cpp_app "$@"
