#!/usr/bin/env bash
# e2e_run_cpp_windows — Cross-compile a C++ app del registry para Windows
# con mingw-w64, deploy al Desktop de Windows (matando una posible instancia
# previa con taskkill.exe), lanzar el .exe nativamente desde WSL y devolver
# stdout + exit code. Pensado para apps tipo headless smoke / regression
# test (ej. altsnap_jitter_test) que arrancan, ejecutan un guion y salen.
#
# Uso (funcion via source):
#     source bash/functions/infra/e2e_run_cpp_windows.sh
#     e2e_run_cpp_windows altsnap_jitter_test          # build + deploy + run
#     e2e_run_cpp_windows altsnap_jitter_test --no-build   # solo deploy + run
#     e2e_run_cpp_windows altsnap_jitter_test --no-deploy  # solo run (asume ya esta en Desktop)
#
# Requisitos:
#   - WSL2 con interop a Windows habilitado (cmd.exe / taskkill.exe en PATH).
#   - mingw-w64 instalado: sudo apt install mingw-w64
#   - cpp/build/windows/ configurable via build_cpp_windows.sh.
#   - C:\Users\lucas\Desktop accesible bajo /mnt/c/Users/lucas/Desktop.
#
# Salida:
#   - stdout/stderr del .exe se imprimen tal cual.
#   - Exit code de la funcion = exit code del .exe (0 = pass).

e2e_run_cpp_windows() {
    set -euo pipefail
    local target="${1:-}"
    if [ -z "$target" ]; then
        echo "[e2e_run_cpp_windows] Uso: e2e_run_cpp_windows <app_name> [--no-build] [--no-deploy]" >&2
        return 2
    fi
    shift
    local do_build=1
    local do_deploy=1
    while [ $# -gt 0 ]; do
        case "$1" in
            --no-build)  do_build=0 ;;
            --no-deploy) do_deploy=0 ;;
            *) echo "[e2e_run_cpp_windows] Flag desconocida: $1" >&2; return 2 ;;
        esac
        shift
    done

    local registry_root="${FN_REGISTRY_ROOT:-}"
    if [ -z "$registry_root" ]; then
        # Walk up from cwd looking for the registry.db sentinel.
        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 "[e2e_run_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 desktop_root="${WIN_DESKTOP_APPS:-/mnt/c/Users/lucas/Desktop/apps}"
    local deploy_dir="$desktop_root/$target"

    # 1. Cross-compile.
    if [ "$do_build" -eq 1 ]; then
        echo "[e2e_run_cpp_windows] cross-compile target=$target" >&2
        # Propagate registry_root so build_cpp_windows doesn't trip over its
        # own BASH_SOURCE-based detection.
        export FN_REGISTRY_ROOT="$registry_root"
        # shellcheck source=./build_cpp_windows.sh
        source "$registry_root/bash/functions/infra/build_cpp_windows.sh"
        build_cpp_windows "$target"
    fi

    # 2. Locate built .exe.
    local exe_src
    exe_src="$(find "$build_dir/apps/$target" -maxdepth 2 -name "${target}.exe" -type f 2>/dev/null | head -1 || true)"
    if [ -z "$exe_src" ]; then
        # Fallback: search the whole build tree (some targets land elsewhere).
        exe_src="$(find "$build_dir" -name "${target}.exe" -type f 2>/dev/null | head -1 || true)"
    fi
    if [ -z "$exe_src" ]; then
        echo "[e2e_run_cpp_windows] No se encontro ${target}.exe en $build_dir" >&2
        return 1
    fi
    echo "[e2e_run_cpp_windows] exe: $exe_src" >&2

    # 3. Deploy a Desktop\apps\<target>.
    if [ "$do_deploy" -eq 1 ]; then
        # Mata instancia previa si esta corriendo (evita "Permission denied" al cp).
        if command -v taskkill.exe &>/dev/null; then
            taskkill.exe /IM "${target}.exe" /F >/dev/null 2>&1 || true
        fi
        mkdir -p "$deploy_dir"
        cp -f "$exe_src" "$deploy_dir/"
        # Copia assets si existen junto al exe (TTFs, runtime, ...).
        local exe_dir
        exe_dir="$(dirname "$exe_src")"
        for sidecar in assets runtime enrichers; do
            if [ -d "$exe_dir/$sidecar" ]; then
                cp -rf "$exe_dir/$sidecar" "$deploy_dir/"
            fi
        done
        # DLLs sueltos (mingw runtime, sqlite, etc.) si los hubiera.
        find "$exe_dir" -maxdepth 1 -name "*.dll" -exec cp -f {} "$deploy_dir/" \; 2>/dev/null || true
        echo "[e2e_run_cpp_windows] deployed -> $deploy_dir" >&2
    fi

    # 4. Run desde WSL. cd al deploy_dir para que exe_dir() apunte al sitio
    #    correcto (local_files/imgui.ini se crea ahi).
    if [ ! -x "$deploy_dir/${target}.exe" ]; then
        echo "[e2e_run_cpp_windows] No hay ${target}.exe en $deploy_dir" >&2
        return 1
    fi
    echo "[e2e_run_cpp_windows] launch $deploy_dir/${target}.exe" >&2
    (
        cd "$deploy_dir"
        ./"${target}.exe"
    )
    local rc=$?
    echo "[e2e_run_cpp_windows] exit=$rc" >&2
    return "$rc"
}

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