#!/bin/bash
# fnva environment setup (eval "$(fnva env --shell bash)")

# --- Auto-restore on startup ---
_fnva_autoload_done=false
fnva_autoload_default() {
    if [[ $_fnva_autoload_done == "true" ]]; then return; fi
    _fnva_autoload_done=true

    local envs_file="$HOME/.fnva/current_envs.toml"
    if [[ -f "$envs_file" ]] && command -v fnva >/dev/null 2>&1; then
        while IFS='=' read -r key value; do
            key=$(echo "$key" | tr -d '[:space:]')
            value=$(echo "$value" | tr -d '[:space:]' | tr -d '"')
            [[ -z "$value" ]] && continue
            local env_script
            env_script=$(fnva "$key" use "$value" 2>/dev/null)
            if [[ -n "$env_script" ]]; then eval "$env_script"; fi
        done < "$envs_file"
    fi
}

fnva_autoload_default

# --- Shell wrapper (auto-source on use) ---
fnva() {
    local __fnva_bin="fnva"
    if [[ $# -ge 2 && ("$1" == "java" || "$1" == "llm" || "$1" == "cc") && "$2" == "use" ]]; then
        local temp_file
        temp_file="$(mktemp)"
        "$__fnva_bin" "$@" > "$temp_file"
        source "$temp_file"
        rm -f "$temp_file"
    else
        "$__fnva_bin" "$@"
    fi
}
