#!/usr/bin/env bash
# Pipeline: compile_wails_app — Resuelve la app Wails desde el nombre o CWD,
# la compila para Windows con wails build y despliega al escritorio + relanza.
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/deploy_wails_exe_to_windows.sh"

compile_wails_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 es una app Wails (no C++) ---
    if [ ! -f "$APP_DIR/wails.json" ]; then
        echo "ERROR: $APP_DIR/wails.json no encontrado." >&2
        echo "La app '$APP' no es una app Wails." >&2
        echo "Si es C++, usa compile_cpp_app en su lugar." >&2
        return 1
    fi

    if [ ! -f "$APP_DIR/go.mod" ]; then
        echo "ERROR: $APP_DIR/go.mod no encontrado." >&2
        echo "Una app Wails requiere go.mod. Ejecuta 'go mod init' en $APP_DIR." >&2
        return 1
    fi

    # --- Paso 2: Compilar para Windows con wails ---
    echo "" >&2
    echo "[2/3] Compilando '$APP' para Windows (wails + mingw)..." >&2

    # Detectar si necesita -tags goolm:
    #   1. app.md declara matrix_crypto_init en uses_functions (E2EE habilitado)
    #   2. wails.json tiene "build:tags": "goolm" (o "buildTags": "goolm")
    local TAGS=""
    local app_md="${APP_DIR}/app.md"
    local wails_json="${APP_DIR}/wails.json"
    local needs_goolm=0

    if [ -f "$app_md" ] && grep -q "matrix_crypto_init" "$app_md" 2>/dev/null; then
        needs_goolm=1
        echo "  Detectado matrix_crypto_init en app.md -> usando -tags goolm" >&2
    fi

    if [ "$needs_goolm" -eq 0 ] && [ -f "$wails_json" ]; then
        if grep -qE '"(build:tags|buildTags)"\s*:\s*"goolm"' "$wails_json" 2>/dev/null; then
            needs_goolm=1
            echo "  Detectado goolm en wails.json -> usando -tags goolm" >&2
        fi
    fi

    if [ "$needs_goolm" -eq 1 ]; then
        TAGS="-tags goolm"
    fi

    (
        cd "$APP_DIR"
        # shellcheck disable=SC2086
        wails build -platform windows/amd64 $TAGS
    )

    # --- Paso 3: Desplegar al escritorio + relanzar ---
    echo "" >&2
    echo "[3/3] Desplegando '$APP' al escritorio + relanzar..." >&2
    deploy_wails_exe_to_windows "$APP" "$APP_DIR"

    # --- Resumen final ---
    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_wails_app: OK =====" >&2
        ls -lh "$final_exe" >&2
    else
        echo "WARN: no se encuentra $final_exe" >&2
    fi
}

compile_wails_app "${1:-}"
