#!/usr/bin/env bash
# muse-cli-node <node> <muse-cli-args...>
# Runs muse-cli inside the node's isolated network namespace with its own
# dedicated Cloudflare WARP egress identity and isolated cookies/config.
# Auto-refreshes cookies via Chromium CDP if authentication fails.
set -euo pipefail

NETVM_BIN="$(cd "$(dirname "$0")" && pwd)"
NODE="${1:?usage: muse-cli-node <node> [args...]}"
shift

CONF_DIR="$HOME/.config/muse-cli/$NODE"
mkdir -p "$CONF_DIR"

run_cli() {
    export MUSE_CONFIG_DIR="$CONF_DIR"
    "$NETVM_BIN/netvm-exec.sh" "$NODE" -- python3 "$NETVM_BIN/muse-cli-inner.py" "$NODE" "$@"
}

# First attempt
set +e
OUTPUT=$(run_cli "$@" 2>&1)
RC=$?
set -e

# Detect authentication failure and trigger single auto-refresh retry
if [ $RC -ne 0 ] && echo "$OUTPUT" | grep -qiE "AuthError|hatch_sess|401|unauthorized"; then
    echo "Notice: Auth failure detected for $NODE; refreshing cookies from Chromium CDP..." >&2
    if "$NETVM_BIN/netvm-exec.sh" "$NODE" -- python3 "$NETVM_BIN/refresh-node-cookies.py" "$NODE"; then
        echo "Notice: Cookies refreshed for $NODE. Retrying operation..." >&2
        run_cli "$@"
        exit $?
    fi
fi

# If succeeded or failed on something else, emit output and exit with RC
echo "$OUTPUT"
exit $RC
