#!/bin/bash
# generate-join-token.sh · 签发节点加入邀请码 v1.0
# 铸渊共享节点池 · 仅冰朔/铸渊运行

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/pool-utils.sh"

TOKENS_FILE="${ZHUYUAN_BASE}/data/join-tokens.json"
MODE=""; TEAM_ID=""; NOTE=""; REVOKE_ID=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --team) TEAM_ID="$2"; shift 2;; --note) NOTE="$2"; shift 2;; --list) MODE="list"; shift;;
    --revoke) MODE="revoke"; REVOKE_ID="$2"; shift 2;; *) MODE="generate"; break;;
  esac
done
[[ -z "$MODE" ]] && { echo "用法: bash generate-join-token.sh --team <团队> [--note 备注]"; exit 1; }

mkdir -p "$(dirname "$TOKENS_FILE")"
[[ ! -f "$TOKENS_FILE" ]] && echo '{"tokens":[]}' > "$TOKENS_FILE"

# 列表
if [[ "$MODE" == "list" ]]; then
  print_header; echo "当前邀请码:"
  python3 -c "import json; data=json.load(open('$TOKENS_FILE')); [print(f\"  {t['token_id']} | {t.get('for_team','?')} | 已用{t['used']}/{t.get('max_uses',1)} | {t.get('note','')}\") for t in data.get('tokens',[])]" 2>/dev/null || echo "无法读取"
  echo ""; exit 0
fi

# 撤销
if [[ "$MODE" == "revoke" ]]; then
  [[ -z "$REVOKE_ID" ]] && { log_err "缺少 token_id"; exit 1; }
  python3 -c "import json; data=json.load(open('$TOKENS_FILE')); data['tokens']=[t for t in data.get('tokens',[]) if t['token_id']!='$REVOKE_ID']; json.dump(data,open('$TOKENS_FILE','w'),indent=2,ensure_ascii=False); print(f'✅ 已撤销: $REVOKE_ID')"
  exit 0
fi

# 签发
[[ -z "$TEAM_ID" ]] && { log_err "缺少团队标识"; exit 1; }
local raw_token=$(python3 -c "import secrets; print('jt_' + secrets.token_hex(16))")
local token_hash=$(echo -n "$raw_token" | sha256sum | cut -d' ' -f1)
local token_id="jt_$(date +%Y%m%d)_$(python3 -c "import secrets; print(secrets.token_hex(3))")"

python3 -c "
import json
data=json.load(open('$TOKENS_FILE'))
data.setdefault('tokens',[]).append({
  'token_hash':'$token_hash','token_id':'$token_id','token_prefix':'${raw_token:0:8}...',
  'for_team':'$TEAM_ID','for_side':'team','max_uses':1,'used':0,
  'created_by':'ICE-GL-ZY001','created_at':'$(date -Iseconds)',
  'expires_at':'$(date -Iseconds)',
  'note':'${NOTE:-$TEAM_ID团队新节点加入}'
})
json.dump(data,open('$TOKENS_FILE','w'),indent=2,ensure_ascii=False)
"

echo ""; echo -e "${C_GREEN}${ICON_OK} 邀请码已签发${C_RESET}"
echo "  令牌ID: ${token_id} | 团队: ${TEAM_ID}"
echo "  令牌: ${C_BOLD}${raw_token}${C_RESET}"
echo "  使用方式: bash <(curl -fsSL https://guanghulab.com/pool/join-pool.sh) --token ${raw_token} --team ${TEAM_ID}"
echo ""
unset raw_token