
#!/usr/bin/env bash
# ============================================================
# BitHunter PROX Wallet Manager
# Proxima v1.6.9 | Manager v1.7.7
# Ubuntu 22.04 / 24.04
#
# Wallet + Node in one directory
# Remote first -> Local fallback
#
# ============================================================

set -Eeuo pipefail

VERSION="1.7.7"

# Dedicated private wallet directory, independent of the launch location.
ROOT="$HOME/.prox/wallet"
mkdir -p -- "$ROOT"
chmod 700 -- "$ROOT"
cd -- "$ROOT"

KEY_FILE="$ROOT/proxima.key"
WALLET_CONFIG="$ROOT/proxi.yaml"
NODE_CONFIG="$ROOT/proxima.yaml"
ACTIVE_FILE="$ROOT/.active_node_url"
BACKUP_DIR="$ROOT/backups"

LOCAL_NODE="http://127.0.0.1:8000"

REMOTE_NODES=(
    "http://79.137.70.25:8001"
    "http://51.254.47.76:8001"
)

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

info() {
    echo -e "${GREEN}[INFO]${NC} $*"
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $*"
}

error() {
    echo -e "${RED}[ERROR]${NC} $*"
}

success() {
    echo -e "${CYAN}[SUCCESS]${NC} $*"
}

pause() {
    echo
    read -rp "按 Enter 返回菜单..."
}


# ------------------------------------------------------------
# 0. Download missing official binaries from GitHub Release
# ------------------------------------------------------------

GITHUB_REPO="lunfardo314/proxima"
RELEASE_TAG="v1.6.9"
RELEASE_API="https://api.github.com/repos/${GITHUB_REPO}/releases/tags/${RELEASE_TAG}"

download_missing_binaries() {
    local requested="${1:-both}"
    local machine
    local release_json
    local tmpdir
    local asset_name
    local asset_url
    local archive
    local member
    local base
    local found_proxi=0
    local found_proxima=0

    # Never overwrite an existing executable.
    [[ -x "$ROOT/proxi" ]] && found_proxi=1
    [[ -x "$ROOT/proxima" ]] && found_proxima=1

    case "$requested" in
        proxi)   found_proxima=1 ;;
        proxima) found_proxi=1 ;;
        both)    ;;
        *)
            error "内部错误：未知程序类型 $requested"
            return 1
            ;;
    esac

    if [[ "$found_proxi" -eq 1 && "$found_proxima" -eq 1 ]]; then
        info "所需官方程序已存在，无需下载。"
        return 0
    fi

    machine="$(uname -m)"
    case "$machine" in
        x86_64|amd64) machine_pattern='(amd64|x86_64)' ;;
        aarch64|arm64) machine_pattern='(arm64|aarch64)' ;;
        *)
            error "暂不支持自动识别的 CPU 架构：$machine"
            return 1
            ;;
    esac

    info "本地缺少官方程序，正在检查 GitHub ${RELEASE_TAG} Release 资源..."
    release_json="$(curl -fsSL --retry 3 --connect-timeout 10 "$RELEASE_API")" || {
        error "无法读取 GitHub Release 信息：$RELEASE_API"
        return 1
    }

    tmpdir="$(mktemp -d "$ROOT/.prox-download.XXXXXX")"
    chmod 700 "$tmpdir"

    # Only consider assets explicitly labelled for Linux and this CPU architecture.
    # Do not guess asset URLs or download binaries from third-party sites.
    while IFS=$'\t' read -r asset_name asset_url; do
        [[ -n "$asset_name" && -n "$asset_url" ]] || continue
        echo
        info "检查官方资源：$asset_name"

        archive="$tmpdir/$asset_name"
        if ! curl -fL --retry 3 --connect-timeout 10 "$asset_url" -o "$archive"; then
            warn "下载失败，跳过：$asset_name"
            continue
        fi

        # A release may publish either standalone binaries or an archive.
        if [[ "$asset_name" =~ (^|[^a-z])proxi([^a-z]|$) ]] &&
           [[ ! "$asset_name" =~ \.(tar\.gz|tgz|zip)$ ]]; then
            install -m 700 "$archive" "$ROOT/proxi"
            found_proxi=1
            success "已安装 proxi"
            continue
        fi

        if [[ "$asset_name" =~ (^|[^a-z])proxima([^a-z]|$) ]] &&
           [[ ! "$asset_name" =~ \.(tar\.gz|tgz|zip)$ ]]; then
            install -m 700 "$archive" "$ROOT/proxima"
            found_proxima=1
            success "已安装 proxima"
            continue
        fi

        # Extract only the two expected executable files from an archive.
        if [[ "$asset_name" == *.tar.gz || "$asset_name" == *.tgz ]]; then
            while IFS= read -r member; do
                base="${member##*/}"
                case "$base" in
                    proxi)
                        if [[ "$found_proxi" -eq 0 ]]; then
                            if tar -xOzf "$archive" "$member" > "$ROOT/proxi"; then
                                chmod 700 "$ROOT/proxi"
                                found_proxi=1
                                success "已从官方压缩包提取 proxi"
                            fi
                        fi
                        ;;
                    proxima)
                        if [[ "$found_proxima" -eq 0 ]]; then
                            if tar -xOzf "$archive" "$member" > "$ROOT/proxima"; then
                                chmod 700 "$ROOT/proxima"
                                found_proxima=1
                                success "已从官方压缩包提取 proxima"
                            fi
                        fi
                        ;;
                esac
            done < <(tar -tzf "$archive" 2>/dev/null || true)
        elif [[ "$asset_name" == *.zip ]]; then
            if ! command -v unzip >/dev/null 2>&1; then
                warn "发现 ZIP 资源，但系统未安装 unzip，无法解压 $asset_name"
                continue
            fi
            while IFS= read -r member; do
                base="${member##*/}"
                case "$base" in
                    proxi)
                        if [[ "$found_proxi" -eq 0 ]]; then
                            if unzip -p "$archive" "$member" > "$ROOT/proxi"; then
                                chmod 700 "$ROOT/proxi"
                                found_proxi=1
                                success "已从官方 ZIP 提取 proxi"
                            fi
                        fi
                        ;;
                    proxima)
                        if [[ "$found_proxima" -eq 0 ]]; then
                            if unzip -p "$archive" "$member" > "$ROOT/proxima"; then
                                chmod 700 "$ROOT/proxima"
                                found_proxima=1
                                success "已从官方 ZIP 提取 proxima"
                            fi
                        fi
                        ;;
                esac
            done < <(unzip -Z1 "$archive" 2>/dev/null || true)
        fi

        case "$requested" in
            proxi)   [[ -x "$ROOT/proxi" ]] && break ;;
            proxima) [[ -x "$ROOT/proxima" ]] && break ;;
            both)    [[ -x "$ROOT/proxi" && -x "$ROOT/proxima" ]] && break ;;
        esac
    done < <(
        jq -r --arg want "$requested" '
          .assets[]
          | select(
              if $want == "both" then
                (.name | test("proxi|proxima"; "i"))
              else
                (.name | test($want; "i"))
              end
            )
          | [.name, .browser_download_url]
          | @tsv
        ' <<< "$release_json"
    )

    rm -rf "$tmpdir"

    case "$requested" in
        proxi)   [[ -x "$ROOT/proxi" ]] && return 0 ;;
        proxima) [[ -x "$ROOT/proxima" ]] && return 0 ;;
        both)    [[ -x "$ROOT/proxi" && -x "$ROOT/proxima" ]] && return 0 ;;
    esac

    if [[ "$requested" == "proxi" || "$requested" == "proxima" || "$requested" == "both" ]]; then
        error "官方 Release 中未找到可识别的 ${requested} 程序资源，或资源内不包含对应可执行文件。"
        echo "请检查官方 Release：https://github.com/${GITHUB_REPO}/releases/tag/${RELEASE_TAG}"
        echo "脚本不会擅自使用第三方下载地址，也不会用猜测的文件名替代官方程序。"
        return 1
    fi

    success "官方程序已准备完成。"
    return 0
}

# ------------------------------------------------------------
# 1. Locate official binaries
# ------------------------------------------------------------

find_binary() {
    local name="$1"

    if [[ -x "$ROOT/$name" ]]; then
        echo "$ROOT/$name"
    elif command -v "$name" >/dev/null 2>&1; then
        command -v "$name"
    else
        return 1
    fi
}


check_dependencies() {
    local missing=()

    for cmd in curl jq python3 screen; do
        if ! command -v "$cmd" >/dev/null 2>&1; then
            missing+=("$cmd")
        fi
    done

    if [[ ${#missing[@]} -gt 0 ]]; then
        error "缺少依赖：${missing[*]}"
        echo
        echo "请执行："
        echo "sudo apt update"
        echo "sudo apt install -y curl jq python3 screen"
        return 1
    fi

    return 0
}

check_required_commands() {
    local missing=()
    local cmd
    for cmd in "$@"; do
        command -v "$cmd" >/dev/null 2>&1 || missing+=("$cmd")
    done
    if [[ ${#missing[@]} -gt 0 ]]; then
        error "当前功能缺少依赖：${missing[*]}"
        echo "请执行：sudo apt update && sudo apt install -y curl jq python3 screen"
        return 1
    fi
}

ensure_program() {
    local name="$1"
    local path=""

    case "$name" in
        proxi)   path="$(find_binary proxi || true)" ;;
        proxima) path="$(find_binary proxima || true)" ;;
        *)
            error "未知程序：$name"
            return 1
            ;;
    esac

    if [[ -n "$path" ]]; then
        case "$name" in
            proxi) PROXI="$path" ;;
            proxima) PROXIMA="$path" ;;
        esac
        return 0
    fi

    info "本地未找到 $name，现在才开始从官方 GitHub ${RELEASE_TAG} Release 下载..."
    check_required_commands curl jq || return 1
    download_missing_binaries "$name" || return 1

    path="$(find_binary "$name" || true)"
    if [[ -z "$path" ]]; then
        error "$name 下载后仍无法执行。"
        return 1
    fi

    case "$name" in
        proxi) PROXI="$path" ;;
        proxima) PROXIMA="$path" ;;
    esac
    return 0
}

# ------------------------------------------------------------
# 2. Wallet information
# ------------------------------------------------------------

get_holder_id() {
    # Parse YAML holder_id safely; normalize CRLF, BOM, quotes and whitespace.
    # Only the public holder ID is read, never the private key.
    [[ -f "$WALLET_CONFIG" ]] || return 1
    python3 - "$WALLET_CONFIG" <<'PYHOLDER'
import re
import sys
from pathlib import Path
try:
    text = Path(sys.argv[1]).read_text(encoding="utf-8-sig")
    match = re.search(r'(?im)^[ \t]*holder_id[ \t]*:[ \t]*(.*)$', text)
    if not match:
        raise ValueError("missing holder_id")
    value = match.group(1).strip().strip('\"\'').strip()
    if not re.fullmatch(r'[0-9a-fA-F]{64}', value):
        raise ValueError("invalid holder_id")
    print(value.lower())
except (OSError, UnicodeError, ValueError):
    sys.exit(1)
PYHOLDER
}

wallet_ready() {
    [[ -f "$KEY_FILE" && -f "$WALLET_CONFIG" ]]
}

# ------------------------------------------------------------
# 3. Create wallet
# ------------------------------------------------------------

create_wallet() {
    echo
    echo "======================================"
    echo "          CREATE PROX WALLET"
    echo "======================================"

    if wallet_ready; then
        warn "检测到已有钱包，不会覆盖。"
        echo
        echo "Holder ID:"
        get_holder_id
        return
    fi

    if [[ -f "$KEY_FILE" || -f "$WALLET_CONFIG" ]]; then
        error "检测到不完整的钱包文件。"
        echo "为防止覆盖原有密钥，请先检查文件。"
        return 1
    fi

    info "开始调用官方钱包创建命令..."
    echo
    echo "请按提示操作。"
    echo "建议给私钥文件设置加密密码。"
    echo

    # Ensure PROXI is resolved before invoking it. This prevents the
    # empty-command error: environment: line ...: : command not found.
    if ! ensure_program proxi; then
        error "无法找到或准备官方 proxi 钱包程序。"
        return 1
    fi

    if [[ -z "${PROXI:-}" || ! -x "$PROXI" ]]; then
        error "proxi 程序路径无效或没有执行权限：${PROXI:-<empty>}"
        return 1
    fi

    # Handle CLI failure without terminating the entire menu under set -e.
    if ! "$PROXI" config wallet; then
        error "官方钱包创建命令执行失败，请检查上方错误信息。"
        return 1
    fi

    if ! wallet_ready; then
        error "钱包创建未完成，未检测到 proxima.key 和 proxi.yaml。"
        return 1
    fi

    chmod 600 "$KEY_FILE" "$WALLET_CONFIG"

    echo
    success "钱包创建成功！"

    echo
    echo "Holder ID:"
    get_holder_id

    echo
    echo "钱包地址:"
    echo "a/$(get_holder_id)"

    warn "请立即备份 proxima.key！"
}


# ------------------------------------------------------------
# Verify encrypted wallet password locally (no node / transfer)
# ------------------------------------------------------------
verify_wallet_ownership() {
    echo
    echo "======================================"
    echo "   VERIFY WALLET OWNERSHIP (OFFLINE)"
    echo "======================================"
    if ! wallet_ready; then
        error "钱包文件不存在，请先创建钱包。"
        return 1
    fi
    if [[ -L "$KEY_FILE" || -L "$WALLET_CONFIG" ]]; then
        error "为保护密钥，不接受符号链接形式的钱包文件。"
        return 1
    fi
    if ! command -v go >/dev/null 2>&1; then
        error "需要安装 Go 编译环境。"
        return 1
    fi
    local holder helper_dir helper
    holder="$(get_holder_id || true)"
    if [[ ! "$holder" =~ ^[0-9a-fA-F]{64}$ ]]; then
        error "无法正确读取 proxi.yaml 中的 Holder ID；请检查文件内容及编码。"
        return 1
    fi
    helper_dir="$ROOT/.wallet_verify"
    helper="$helper_dir/verify_ownership"
    mkdir -p "$helper_dir"
    chmod 700 "$helper_dir"
    # Compile from the pinned official Proxima keystore package.
    # Never print or transmit decrypted private key material.
    cat > "$helper_dir/ownership.go" <<'GOOWN'
package main

import (
    "crypto/ed25519"
    "crypto/rand"
    "crypto/subtle"
    "fmt"
    "os"
    "strings"

    "github.com/lunfardo314/proxima/util/keystore"
    "golang.org/x/term"
)

func fail(msg string) {
    fmt.Fprintln(os.Stderr, "[ERROR]", msg)
    os.Exit(1)
}

func main() {
    if len(os.Args) != 3 { fail("缺少钱包路径或 Holder ID") }
    ks, err := keystore.LoadFromFile(os.Args[1])
    if err != nil { fail("无法读取官方钱包密钥格式") }
    expected := strings.ToLower(strings.TrimSpace(os.Args[2]))
    if ks.KeyType != keystore.KeyTypeED25519 { fail("暂不支持此密钥类型") }
    if !strings.EqualFold(strings.TrimSpace(ks.HolderID), expected) {
        fail("proxima.key 与 proxi.yaml 的 Holder ID 不一致")
    }
    var pass []byte
    if ks.IsEncrypted() {
        fmt.Print("请输入钱包密码（输入不可见）: ")
        pass, err = term.ReadPassword(int(os.Stdin.Fd()))
        fmt.Println()
        if err != nil { fail("无法从终端安全读取密码") }
    } else {
        fmt.Println("[WARN] 钱包私钥未加密：无需密码，但任何持有文件的人都可能控制钱包。")
    }
    private, err := ks.GetPrivateKey(string(pass))
    for i := range pass { pass[i] = 0 }
    if err != nil { fail("密钥解密或公钥一致性检查失败（可能密码错误）") }
    defer func() { for i := range private { private[i] = 0 } }()
    var sk ed25519.PrivateKey
    switch len(private) {
    case ed25519.SeedSize:
        sk = ed25519.NewKeyFromSeed(private)
    case ed25519.PrivateKeySize:
        sk = ed25519.PrivateKey(private)
    default:
        fail("私钥长度不符合 ED25519 格式")
    }
    public, err := keystore.PublicKeyBytes(ks)
    if err != nil || len(public) != ed25519.PublicKeySize {
        fail("无法读取钱包公钥")
    }
    derived := sk.Public().(ed25519.PublicKey)
    if subtle.ConstantTimeCompare(derived, public) != 1 {
        fail("解密私钥与钱包公钥不匹配")
    }
    challenge := make([]byte, 32)
    if _, err := rand.Read(challenge); err != nil { fail("无法生成随机挑战") }
    message := append([]byte("BitHunter PROX wallet ownership proof v1\x00"), challenge...)
    signature := ed25519.Sign(sk, message)
    if !ed25519.Verify(ed25519.PublicKey(public), message, signature) {
        fail("签名验证失败")
    }
    fmt.Println("[SUCCESS] 本地随机挑战签名验证成功。")
    fmt.Println("[SUCCESS] 解密私钥与密钥文件公钥匹配；钱包配置 Holder ID 与密钥文件一致。")
    fmt.Println("Holder ID:", expected)
    fmt.Println("[INFO] 此验证不连接节点、不转账，也不证明私钥没有被他人复制。")
}
GOOWN
    chmod 600 "$helper_dir/ownership.go"
    info "准备离线所有权验证工具（首次运行需下载 Go 依赖）..."
    if ! (
        cd "$helper_dir" &&
        if [[ ! -f go.mod ]]; then go mod init bithunter-wallet-ownership; fi &&
        go get github.com/lunfardo314/proxima@v1.6.9 &&
        go get golang.org/x/term &&
        go mod tidy &&
        go build -o "$helper" ./ownership.go
    ); then
        error "验证工具编译失败，未执行所有权验证。"
        return 1
    fi
    chmod 700 "$helper"
    "$helper" "$KEY_FILE" "$holder"
}

# ------------------------------------------------------------
# 4. Node API status
# ------------------------------------------------------------

# Return:
# 0 = API online and synchronized
# 2 = API online but still syncing
# 1 = unavailable or invalid response

probe_node() {
    local url="${1%/}"
    local info_json
    local sync_json

    info_json="$(curl -fsS \
        --connect-timeout 5 \
        --max-time 10 \
        "$url/api/v1/node_info" 2>/dev/null)" || return 1

    sync_json="$(curl -fsS \
        --connect-timeout 5 \
        --max-time 10 \
        "$url/api/v1/sync_info" 2>/dev/null)" || return 1

    if ! jq -e '(.version != null) and
        ((.error // "") == "")' <<< "$info_json" >/dev/null; then
        return 1
    fi

    if ! jq -e '(.synced != null) and
        ((.error // "") == "")' <<< "$sync_json" >/dev/null; then
        return 1
    fi

    if jq -e '.synced == true' <<< "$sync_json" >/dev/null; then
        return 0
    fi

    return 2
}

show_node_info() {
    local url="${1%/}"
    local info_json sync_json

    info_json="$(curl -fsS --max-time 10 \
        "$url/api/v1/node_info")" || return 1

    sync_json="$(curl -fsS --max-time 10 \
        "$url/api/v1/sync_info")" || return 1

    echo "API: $url"

    echo "Version:"
    jq -r '.version // "Unknown"' <<< "$info_json"

    echo "Current slot:"
    jq -r '.current_slot // "Unknown"' <<< "$sync_json"

    echo "LRB slot:"
    jq -r '.lrb_slot // "Unknown"' <<< "$sync_json"

    echo "Synchronized:"
    jq -r '.synced // false' <<< "$sync_json"
}

set_active_node() {
    local url="$1"

    echo "$url" > "$ACTIVE_FILE"
    chmod 600 "$ACTIVE_FILE"

    success "当前节点：$url"
}

# ------------------------------------------------------------
# 5. Test official remote nodes
# ------------------------------------------------------------

connect_remote() {
    local url
    local status

    check_required_commands curl jq || return 1
    echo
    info "优先检测官方远程节点..."

    for url in "${REMOTE_NODES[@]}"; do
        echo
        echo "Testing: $url"

        if probe_node "$url"; then
            success "远程节点正常并已同步。"
            set_active_node "$url"
            return 0
        else
            status=$?

            if [[ "$status" -eq 2 ]]; then
                warn "节点在线，但还未同步。"
            else
                warn "远程节点无法使用。"
            fi
        fi
    done

    return 1
}

# ------------------------------------------------------------
# 6. Prepare official local node launcher
# ------------------------------------------------------------

prepare_node_launcher() {
    # This function may also be called independently; validate both binaries.
    if ! ensure_program proxi; then
        error "找不到或无法准备官方 proxi 钱包程序。"
        return 1
    fi

    if ! ensure_program proxima; then
        error "找不到或无法准备官方 proxima 节点程序。"
        return 1
    fi

    if [[ -z "${PROXIMA:-}" || ! -x "$PROXIMA" ]]; then
        error "proxima 程序路径无效或没有执行权限：${PROXIMA:-<empty>}"
        return 1
    fi

    if [[ ! -f "$NODE_CONFIG" ]]; then
        info "生成官方本地节点配置..."
        if ! "$PROXI" config node; then
            error "官方节点配置生成命令执行失败。"
            return 1
        fi

        if [[ ! -f "$NODE_CONFIG" ]]; then
            error "proxima.yaml 创建失败。"
            return 1
        fi

        chmod 600 "$NODE_CONFIG"
    fi

    # Official run_proxima.sh behavior:
    # encrypted keystore prompts for its passphrase.

    if [[ ! -f "$ROOT/run_proxima.sh" ]]; then
        cat > "$ROOT/run_proxima.sh" <<'LAUNCHER'
#!/usr/bin/env bash

set -e

cd "$(dirname "$0")"

export PATH="$PWD:$PATH"

if [ ! -f proxima.key ]; then
    echo "Error: proxima.key not found" >&2
    exit 1
fi

if grep -q '"crypto"' proxima.key; then
    read -s -p "Enter passphrase for proxima.key: " PASSPHRASE
    echo

    if [ -z "$PASSPHRASE" ]; then
        echo "Empty passphrase"
        exit 1
    fi

    SEQUENCER_KEY_PASSPHRASE="$PASSPHRASE" exec proxima
else
    exec proxima
fi
LAUNCHER

        chmod 700 "$ROOT/run_proxima.sh"
    fi

    return 0
}

# ------------------------------------------------------------
# 7. Start local node
# ------------------------------------------------------------

start_local_node() {
    echo
    echo "======================================"
    echo "          START LOCAL NODE"
    echo "======================================"

    if ! wallet_ready; then
        error "请先创建钱包。"
        return 1
    fi

    if probe_node "$LOCAL_NODE"; then
        success "本地节点已经运行。"
        set_active_node "$LOCAL_NODE"
        return 0
    fi

    ensure_program proxi || return 1
    ensure_program proxima || return 1
    check_required_commands screen curl jq || return 1
    prepare_node_launcher || return 1

    if screen -list | grep -q 'prox-node'; then
        warn "检测到已有本地节点 screen 会话。"
    else
        info "正在启动本地 Proxima 节点..."

        local quoted_root
        printf -v quoted_root '%q' "$ROOT"

        screen -dmS prox-node \
            bash -lc "cd $quoted_root && ./run_proxima.sh"

        sleep 3
    fi

    echo
    echo "本地节点 screen 会话：prox-node"
    echo
    echo "如果钱包密钥已经加密："
    echo "运行 screen -r prox-node"
    echo "输入钱包密码后，按 Ctrl+A 再按 D 返回。"

    echo
    info "等待本地节点启动及同步..."

    local i
    for i in $(seq 1 120); do
        if probe_node "$LOCAL_NODE"; then
            success "本地节点已同步！"
            set_active_node "$LOCAL_NODE"
            return 0
        fi

        sleep 1
    done

    if probe_node "$LOCAL_NODE"; then
        set_active_node "$LOCAL_NODE"
        return 0
    fi

    warn "节点尚未完成同步或尚未开放 API。"
    echo "可以稍后重新检查，不要使用未同步节点进行转账。"

    return 1
}

# ------------------------------------------------------------
# 8. Automatic node selection
# ------------------------------------------------------------

auto_connect() {
    local status

    if [[ -f "$ACTIVE_FILE" ]]; then
        local old_url
        old_url="$(cat "$ACTIVE_FILE")"

        if [[ -n "$old_url" ]] && probe_node "$old_url"; then
            info "继续使用上次成功连接的节点。"
            return 0
        fi
    fi

    if connect_remote; then
        return 0
    fi

    warn "远程节点均不可用或未同步。"
    warn "切换到本地节点。"

    start_local_node
}

ensure_node() {
    local url
    local status

    if [[ -f "$ACTIVE_FILE" ]]; then
        url="$(cat "$ACTIVE_FILE")"

        if [[ -n "$url" ]] && probe_node "$url"; then
            return 0
        fi
    fi

    auto_connect
}

# ------------------------------------------------------------
# 9. Node menu
# ------------------------------------------------------------

node_menu() {
    local choice

    while true; do
        echo
        echo "======================================"
        echo "           NODE MANAGER"
        echo "======================================"
        echo "1. 自动连接（远程优先，本地备用）"
        echo "2. 仅连接官方远程节点"
        echo "3. 启动本地节点"
        echo "4. 查看当前节点状态"
        echo "0. 返回主菜单"
        echo "======================================"

        read -rp "请选择: " choice

        case "$choice" in
            1)
                auto_connect
                pause
                ;;
            2)
                if connect_remote; then
                    :
                else
                    error "没有可用的远程节点。"
                fi
                pause
                ;;
            3)
                start_local_node
                pause
                ;;
            4)
                if [[ -f "$ACTIVE_FILE" ]]; then
                    show_node_info "$(cat "$ACTIVE_FILE")" || \
                        warn "当前节点不可用。"
                else
                    warn "尚未选择节点。"
                fi
                pause
                ;;
            0)
                return
                ;;
            *)
                warn "无效选择。"
                ;;
        esac
    done
}

# ------------------------------------------------------------
# 10. Query wallet balance
# ------------------------------------------------------------

query_balance() {
    echo
    echo "======================================"
    echo "           PROX BALANCE"
    echo "======================================"

    if ! wallet_ready; then
        error "请先创建钱包。"
        return 1
    fi

    ensure_program proxi || return 1
    check_required_commands curl jq || return 1

    if ! ensure_node; then
        error "没有可用且已同步的节点。"
        return 1
    fi

    local url
    url="$(cat "$ACTIVE_FILE")"

    echo
    echo "Holder ID:"
    get_holder_id

    echo
    echo "钱包地址:"
    echo "a/$(get_holder_id)"

    echo
    echo "节点:"
    echo "$url"

    echo
    info "正在查询链上余额..."

    "$PROXI" --config proxi \
        node --api.node_url "$url" balance
}

# ------------------------------------------------------------
# 11. Convert PROX to smallest ledger units
# ------------------------------------------------------------

convert_amount() {
    local amount="$1"
    local rate="$2"

    python3 - "$amount" "$rate" <<'PY'
import sys
from decimal import Decimal, InvalidOperation

try:
    amount = Decimal(sys.argv[1])
    rate = Decimal(sys.argv[2])

    if not amount.is_finite() or amount <= 0:
        raise ValueError("Amount must be positive")

    result = amount * rate

    if result != result.to_integral_value():
        raise ValueError("Too many decimal places")

    print(int(result))

except (InvalidOperation, ValueError) as e:
    print(f"Invalid amount: {e}", file=sys.stderr)
    sys.exit(1)
PY
}

# ------------------------------------------------------------
# 12. PROX transfer
# ------------------------------------------------------------

transfer_prox() {
    local target
    local amount
    local rate
    local motes
    local url
    local constants

    echo
    echo "======================================"
    echo "             PROX TRANSFER"
    echo "======================================"

    if ! wallet_ready; then
        error "请先创建钱包。"
        return 1
    fi

    ensure_program proxi || return 1
    check_required_commands curl jq python3 || return 1

    if ! ensure_node; then
        error "没有可用且已同步的节点。"
        return 1
    fi

    url="$(cat "$ACTIVE_FILE")"

    echo
    echo "当前钱包:"
    echo "a/$(get_holder_id)"

    echo
    read -rp "收款 Holder ID（64位HEX，不带a/）: " target

    target="${target,,}"

    if [[ ! "$target" =~ ^[0-9a-f]{64}$ ]]; then
        error "Holder ID 格式错误。"
        return 1
    fi

    echo
    read -rp "转账数量（PROX）: " amount

    # Fetch official ledger conversion constant.
    constants="$(curl -fsS \
        --connect-timeout 5 \
        --max-time 15 \
        "$url/api/v1/ledger_constants")" || {
            error "无法获取账本精度。"
            return 1
        }

    rate="$(jq -er '.smallest_amounts_per_base_token' \
        <<< "$constants")" || {
            error "无法读取最小单位换算值。"
            return 1
        }

    motes="$(convert_amount "$amount" "$rate")" || return 1

    echo
    echo "--------------------------------------"
    echo "发送钱包: $(get_holder_id)"
    echo "接收钱包: $target"
    echo "转账金额: $amount PROX"
    echo "账本单位: $motes"
    echo "节点: $url"
    echo "--------------------------------------"

    warn "请认真核对收款 Holder ID！"
    warn "网络交易一旦成功提交，通常无法撤销。"

    echo
    read -rp "确认转账请输入 SEND: " confirm

    if [[ "$confirm" != "SEND" ]]; then
        warn "用户取消转账。"
        return 0
    fi

    echo
    info "正在构建、签名并提交交易..."

    "$PROXI" --config proxi \
        node --api.node_url "$url" \
        send_to_wallet "$motes" "$target"

    echo
    success "转账命令执行结束。"
    echo "请以节点返回的交易结果及后续 LRB 查询为准。"
}

# ------------------------------------------------------------
# 13. Backup wallet
# ------------------------------------------------------------

backup_wallet() {
    local dest

    if ! wallet_ready; then
        error "钱包文件不存在。"
        return 1
    fi

    mkdir -p "$BACKUP_DIR"
    chmod 700 "$BACKUP_DIR"

    dest="$BACKUP_DIR/backup_$(date +%Y%m%d_%H%M%S)"

    mkdir -p "$dest"
    chmod 700 "$dest"

    cp "$KEY_FILE" "$dest/"
    cp "$WALLET_CONFIG" "$dest/"

    if [[ -f "$NODE_CONFIG" ]]; then
        cp "$NODE_CONFIG" "$dest/"
    fi

    chmod 600 "$dest"/*

    echo
    success "钱包备份完成。"
    echo "备份目录：$dest"

    warn "备份目录含有私钥，请妥善保管。"
}

# ------------------------------------------------------------
# 14. Main menu
# ------------------------------------------------------------

main_menu() {
    local choice

    while true; do
        clear 2>/dev/null || true

        echo -e "${CYAN}"
        echo "=========================================="
        echo "        BitHunter PROX Wallet"
        echo "              v$VERSION"
        echo "=========================================="
        echo -e "${NC}"

        if wallet_ready; then
            echo -e "钱包状态: ${GREEN}已创建${NC}"
            echo "Holder ID: $(get_holder_id)"
        else
            echo -e "钱包状态: ${YELLOW}未创建${NC}"
        fi

        if [[ -f "$ACTIVE_FILE" ]]; then
            echo "当前节点: $(cat "$ACTIVE_FILE")"
        else
            echo "当前节点: 尚未连接"
        fi

        echo
        echo "------------------------------------------"
        echo "  1. 创建 PROX 钱包"
        echo "  2. 验证钱包所有权（密码 + 签名）"
        echo "  3. 运行节点 / 节点管理"
        echo "  4. 查询钱包余额"
        echo "  5. PROX 转账"
        echo "  6. 备份钱包"
        echo "  0. 退出程序"
        echo "------------------------------------------"

        read -rp "请输入选项: " choice

        case "$choice" in
            1)
                create_wallet
                pause
                ;;
            2)
                verify_wallet_ownership || true
                pause
                ;;
            3)
                node_menu
                ;;
            4)
                query_balance
                pause
                ;;
            5)
                transfer_prox
                pause
                ;;
            6)
                backup_wallet
                pause
                ;;
            0)
                echo
                info "退出 PROX Wallet。"
                exit 0
                ;;
            *)
                warn "无效选项。"
                sleep 1
                ;;
        esac
    done
}

# ------------------------------------------------------------
# START
# ------------------------------------------------------------

# Do not download/check Proxima binaries at startup.
# The management menu is available immediately; each feature checks only
# the executable it actually needs when the user selects that feature.
PROXI="$(find_binary proxi || true)"
PROXIMA="$(find_binary proxima || true)"

mkdir -p "$BACKUP_DIR"
chmod 700 "$BACKUP_DIR"

main_menu
