#!/usr/bin/env bash
# resolve_cpp_app_dir — Resuelve nombre y directorio absoluto de una app C++ del registry.
# Sin arg: deduce desde CWD si esta dentro de apps/<X>/, cpp/apps/<X>/ o projects/*/apps/<X>/.
# Con arg: usa el nombre directamente y busca en las tres ubicaciones.
# Salida: "<app_name>\t<absolute_dir_path>" en stdout (TAB separado), exit 0.
# Error: lista apps disponibles en stderr + exit 1.

resolve_cpp_app_dir() {
    local app_arg="${1:-}"
    local root="${FN_REGISTRY_ROOT:-/home/lucas/fn_registry}"

    _list_cpp_apps() {
        ls "$root/apps/"     2>/dev/null | sed 's/^/  apps\//'
        ls "$root/cpp/apps/" 2>/dev/null | sed 's/^/  cpp\/apps\//'
        for proj in "$root"/projects/*/apps/; do
            ls "$proj" 2>/dev/null | sed "s|^|  $(echo "$proj" | sed "s|$root/||")|"
        done
    }

    # --- Deducir desde CWD si no hay argumento ---
    if [ -z "$app_arg" ]; then
        local cwd
        cwd="$(pwd)"
        case "$cwd" in
            "$root"/apps/*/|"$root"/apps/*)
                local rel="${cwd#"$root/apps/"}"
                app_arg="${rel%%/*}"
                ;;
            "$root"/cpp/apps/*/|"$root"/cpp/apps/*)
                local rel="${cwd#"$root/cpp/apps/"}"
                app_arg="${rel%%/*}"
                ;;
            "$root"/projects/*/apps/*/|"$root"/projects/*/apps/*)
                local rel="${cwd#"$root/projects/"}"
                rel="${rel#*/apps/}"
                app_arg="${rel%%/*}"
                ;;
        esac
    fi

    # --- Aun vacio: listar y abortar ---
    if [ -z "$app_arg" ]; then
        echo "ERROR: no se pudo deducir la app desde el directorio actual." >&2
        echo "" >&2
        echo "Apps disponibles:" >&2
        _list_cpp_apps >&2
        echo "" >&2
        echo "Uso: resolve_cpp_app_dir <app_name>" >&2
        return 1
    fi

    # --- Buscar directorio real ---
    local app_dir=""

    # Primero (issue 0096 canonical): apps/<X>
    if [ -d "$root/apps/$app_arg" ] && [ -f "$root/apps/$app_arg/CMakeLists.txt" ]; then
        app_dir="$root/apps/$app_arg"
    fi

    # Segundo (legacy): cpp/apps/<X>
    if [ -z "$app_dir" ] && [ -d "$root/cpp/apps/$app_arg" ]; then
        app_dir="$root/cpp/apps/$app_arg"
    fi

    # Tercero: projects/*/apps/<X> (primer match)
    if [ -z "$app_dir" ]; then
        for cand in "$root"/projects/*/apps/"$app_arg"; do
            if [ -d "$cand" ]; then
                app_dir="$cand"
                break
            fi
        done
    fi

    if [ -z "$app_dir" ]; then
        echo "ERROR: no se encuentra app '$app_arg' en apps/, cpp/apps/ ni en projects/*/apps/" >&2
        echo "" >&2
        echo "Apps disponibles:" >&2
        _list_cpp_apps >&2
        return 1
    fi

    printf '%s\t%s\n' "$app_arg" "$app_dir"
}

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