#!/usr/bin/env bash
# redeploy_cpp_app_windows — Pipeline orquestador: build (opcional) + deploy + launch + verify
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../infra/build_cpp_windows.sh"
source "$SCRIPT_DIR/../infra/deploy_cpp_exe_to_windows.sh"
source "$SCRIPT_DIR/../infra/launch_cpp_app_windows.sh"
source "$SCRIPT_DIR/../infra/is_cpp_app_running_windows.sh"
source "$SCRIPT_DIR/../infra/refresh_windows_icon_cache.sh"

redeploy_cpp_app_windows() {
    local app_name=""
    local app_dir=""
    local do_build=0

    # Parsear argumentos posicionales y flags
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --build)
                do_build=1
                shift
                ;;
            -*)
                echo "redeploy_cpp_app_windows: flag desconocido: $1" >&2
                return 1
                ;;
            *)
                if [[ -z "$app_name" ]]; then
                    app_name="$1"
                elif [[ -z "$app_dir" ]]; then
                    app_dir="$1"
                else
                    echo "redeploy_cpp_app_windows: argumento inesperado: $1" >&2
                    return 1
                fi
                shift
                ;;
        esac
    done

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

    # Paso 1: build opcional
    if [[ $do_build -eq 1 ]]; then
        echo "[1/4] Building $app_name for Windows..."
        if ! build_cpp_windows "$app_name"; then
            echo "ERROR [build]: build_cpp_windows falló para '$app_name'" >&2
            return 1
        fi
        echo "[1/4] Build OK"
    else
        echo "[1/4] Build skipped (--build no especificado)"
    fi

    # Paso 2: deploy (taskkill + copy exe/DLLs/assets/runtime + preserva local_files)
    echo "[2/4] Deploying $app_name to Windows Desktop..."
    if ! deploy_cpp_exe_to_windows "$app_name" "$app_dir"; then
        echo "ERROR [deploy]: deploy_cpp_exe_to_windows falló para '$app_name'" >&2
        return 1
    fi
    echo "[2/4] Deploy OK"

    # Refrescar cache de iconos del shell. Sin esto el .exe nuevo puede salir
    # con el icono generico (Windows cachea por timestamp/path en iconcache.db
    # y a veces no detecta el cambio inmediatamente). Best-effort: si falla
    # no abortamos el redeploy.
    refresh_windows_icon_cache || true

    # Paso 3: lanzar la app
    echo "[3/4] Launching $app_name..."
    if ! launch_cpp_app_windows "$app_name"; then
        echo "ERROR [launch]: launch_cpp_app_windows falló para '$app_name'" >&2
        return 1
    fi
    echo "[3/4] Launch OK"

    # Paso 4: esperar arranque y verificar
    sleep 1
    echo "[4/4] Verifying $app_name is running..."
    local pid=""
    if ! pid=$(is_cpp_app_running_windows "$app_name"); then
        echo "ERROR [verify]: $app_name no está corriendo tras el lanzamiento. Revisa logs en Desktop/apps/$app_name/." >&2
        return 1
    fi
    echo "[4/4] Running OK"

    local build_label="no"
    [[ $do_build -eq 1 ]] && build_label="yes"
    echo "OK: $app_name redeployed (build=$build_label, PID=$pid)"
}

# Ejecutar si se llama directamente (fn run lo invoca como script)
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    redeploy_cpp_app_windows "$@"
fi
