#!/usr/bin/env bash
# deploy_cpp_exe_to_windows — Copia el .exe compilado (y DLLs, assets, enrichers, runtime)
# desde cpp/build/windows/ al escritorio de Windows /mnt/c/Users/lucas/Desktop/apps/<APP>/.
# Preserva local_files/ (estado del usuario). Pre-authorized: taskkill.exe /F para matar proceso.

deploy_cpp_exe_to_windows() {
    local app="${1:-}"
    local app_dir="${2:-}"

    if [ -z "$app" ] || [ -z "$app_dir" ]; then
        echo "ERROR: uso: deploy_cpp_exe_to_windows <app_name> <app_dir>" >&2
        return 1
    fi

    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}"

    # --- 1. Verificar que el .exe existe ---
    local exe_src="$build_win/apps/$app/$app.exe"
    if [ ! -f "$exe_src" ]; then
        echo "ERROR: no se ha generado $exe_src" >&2
        echo "Compila primero con: build_cpp_windows $app" >&2
        return 1
    fi

    # --- 2. Crear directorios destino ---
    local dest="$win_desktop_apps/$app"
    local assets="$dest/assets"
    mkdir -p "$dest" "$assets"

    # --- 3. Pre-deploy: matar proceso si esta corriendo en Windows ---
    # Windows libera el file handle async tras taskkill. Hacemos poll hasta que
    # el proceso desaparezca de tasklist o se agote el timeout.
    if command -v taskkill.exe >/dev/null 2>&1; then
        taskkill.exe /IM "${app}.exe" /F >/dev/null 2>&1 || true
        local i
        for i in 1 2 3 4 5 6 7 8 9 10; do
            if ! tasklist.exe /FI "IMAGENAME eq ${app}.exe" /NH 2>/dev/null \
                 | grep -qi "^${app}.exe"; then
                break
            fi
            sleep 0.3
        done
    fi

    # --- 4. Copiar .exe al top level con retry ---
    # Windows puede tener el archivo aun bloqueado momentaneamente; reintentar.
    local cp_ok=0
    local attempt
    for attempt in 1 2 3 4 5; do
        if cp -v "$exe_src" "$dest/"; then
            cp_ok=1
            break
        fi
        echo "deploy_cpp_exe_to_windows: cp intento $attempt fallo, reintentando..." >&2
        # Reintentar taskkill por si el proceso resucito o quedo zombie.
        taskkill.exe /IM "${app}.exe" /F >/dev/null 2>&1 || true
        sleep 0.5
    done
    if [ "$cp_ok" -ne 1 ]; then
        echo "ERROR: cp del .exe fallo tras 5 intentos. $exe_src -> $dest/" >&2
        return 1
    fi

    # --- 5. DLLs al top level (Windows DLL search convention) ---
    find "$build_win/apps/$app" -maxdepth 1 -type f -name '*.dll' \
        -exec cp -v {} "$dest/" \;

    # --- 6. assets/ del build (TTFs, etc.) -> dest/assets/ ---
    if [ -d "$build_win/apps/$app/assets" ]; then
        rsync -a --delete "$build_win/apps/$app/assets/" "$assets/"
    fi

    # --- 7. enrichers/ del app_dir -> assets/enrichers/ ---
    if [ -d "$app_dir/enrichers" ]; then
        rsync -a --delete \
            --exclude '__pycache__' \
            --exclude '*.pyc' \
            "$app_dir/enrichers/" "$assets/enrichers/"
    fi

    # --- 7b. collectors/ del app_dir -> assets/collectors/ (odr_console) ---
    if [ -d "$app_dir/collectors" ]; then
        rsync -a --delete \
            --exclude '__pycache__' \
            --exclude '*.pyc' \
            "$app_dir/collectors/" "$assets/collectors/"
    fi

    # --- 8. runtime/ Python embebido -> assets/runtime/ ---
    if grep -q '^python_runtime:[[:space:]]*true' "$app_dir/app.md" 2>/dev/null; then
        if [ ! -d "$app_dir/runtime/python" ] || \
           [ "$app_dir/app.md" -nt "$app_dir/runtime/.lock" ]; then
            echo "[freeze] regenerando runtime Python (Windows) para $app"
            "$app_dir/tools/freeze_python_runtime.sh" "$app_dir" windows
        fi
        rsync -a --delete \
            --exclude '__pycache__' \
            --exclude '*.pyc' \
            "$app_dir/runtime/" "$assets/runtime/"
    fi

    # --- 9. Extras: gx-cli, gx-cli.exe -> assets/ ---
    for extra in gx-cli gx-cli.exe; do
        if [ -f "$app_dir/$extra" ]; then
            cp -v "$app_dir/$extra" "$assets/"
        fi
    done

    # --- 10. NO tocar local_files/ (estado del usuario) ---
    echo ""
    echo "OK: $app -> $dest"
    if [ -d "$dest/local_files" ]; then
        echo "    local_files/ preservado: $(du -sh "$dest/local_files" | cut -f1)"
    fi
}

if [ "${BASH_SOURCE[0]}" = "$0" ]; then
    deploy_cpp_exe_to_windows "$@"
fi
