# shellcheck shell=bash

gwr_find_binary() {
    if [[ -n "${GW_TUI_BIN:-}" && -x "$GW_TUI_BIN" ]]; then
        echo "$GW_TUI_BIN"
        return 0
    fi

    local binary_paths=(
        "$SCRIPT_DIR/orchestra"
        "$SCRIPT_DIR/gw-tui"
        "$SCRIPT_DIR/gw-tui/target/release/gw-tui"
        "$SCRIPT_DIR/gw-tui/target/debug/gw-tui"
        "$(command -v gw-tui 2>/dev/null || true)"
    )

    for path in "${binary_paths[@]}"; do
        if [[ -n "$path" && -f "$path" && -x "$path" ]]; then
            echo "$path"
            return 0
        fi
    done

    return 1
}

gwr_should_check_updates() {
    # Check if we should run update check (once per day)
    local last_check_file="${HOME}/.cache/orchestra/last_update_check"
    local current_time=$(date +%s)
    local last_check=0
    
    if [[ -f "$last_check_file" ]]; then
        last_check=$(cat "$last_check_file" 2>/dev/null || echo 0)
    fi
    
    # Check if more than 24 hours have passed (86400 seconds)
    local time_diff=$((current_time - last_check))
    if [[ $time_diff -gt 86400 ]]; then
        # Create cache directory if it doesn't exist
        mkdir -p "$(dirname "$last_check_file")"
        echo "$current_time" > "$last_check_file"
        return 0
    fi
    
    return 1
}

gwr_check_updates_silent() {
    # Silent update check that doesn't interfere with normal operation
    if gwr_should_check_updates; then
        # Run update check in background, only show if update available
        "$SCRIPT_DIR/shell/gwr/check-updates.sh" 2>/dev/null | grep -E "(⚠️|newer version|Update instructions)" || true
    fi
}
