#!/bin/bash
# NodeSeek 自动签到脚本 v2.0
# 支持多账号、CDP 控制、状态记录

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
STATE_FILE="$SCRIPT_DIR/nodeseek-checkin-state.json"
CDP_URL="http://127.0.0.1:18800"

# 账号配置
declare -A ACCOUNTS=(
    ["menglong"]="dc4d1551406351a93c09082ea08e2d2e"
    ["vp404"]="3cfeb30b562daec31ba63bf64fdb3838"
)
declare -A ACCOUNT_NAMES=(
    ["menglong"]="朦胧"
    ["vp404"]="VP404"
)

# 初始化状态文件
if [ ! -f "$STATE_FILE" ]; then
    echo '{"lastCheckin": null, "accounts": {}}' > "$STATE_FILE"
fi

TODAY=$(date '+%Y-%m-%d')
LAST_CHECKIN=$(jq -r '.lastCheckin // "never"' "$STATE_FILE")

if [ "$LAST_CHECKIN" = "$TODAY" ]; then
    echo "今天已经签到过了 ($TODAY)"
    jq -r '.accounts | to_entries[] | "  \(.key): \(.value.status) (\(.value.reward // "N/A"))"' "$STATE_FILE"
    exit 0
fi

echo "开始签到 NodeSeek ($TODAY)..."

# 签到函数
checkin_account() {
    local key=$1
    local cookie=$2
    local name=${ACCOUNT_NAMES[$key]}
    
    echo "[$name] 签到中..."
    
    # 使用 curl 签到
    response=$(curl -s -X POST "https://www.nodeseek.com/api/attendance?random=false" \
        -H "Cookie: _nk=$cookie" \
        -H "User-Agent: Mozilla/5.0" \
        -H "Accept: application/json")
    
    success=$(echo "$response" | jq -r '.success // false')
    message=$(echo "$response" | jq -r '.message // "未知错误"')
    
    if [ "$success" = "true" ]; then
        reward=$(echo "$response" | jq -r '.data // "未知"')
        echo "[$name] ✅ 签到成功！奖励: $reward"
        jq --arg name "$name" --arg reward "$reward" \
            '.accounts[$name] = {status: "success", reward: $reward, time: now|todate}' \
            "$STATE_FILE" > "$STATE_FILE.tmp" && mv "$STATE_FILE.tmp" "$STATE_FILE"
    else
        echo "[$name] ❌ 签到失败: $message"
        jq --arg name "$name" --arg msg "$message" \
            '.accounts[$name] = {status: "failed", error: $msg, time: now|todate}' \
            "$STATE_FILE" > "$STATE_FILE.tmp" && mv "$STATE_FILE.tmp" "$STATE_FILE"
    fi
}

# 遍历所有账号签到
for key in "${!ACCOUNTS[@]}"; do
    checkin_account "$key" "${ACCOUNTS[$key]}"
    sleep 2
done

# 更新最后签到日期
jq --arg today "$TODAY" '.lastCheckin = $today' "$STATE_FILE" > "$STATE_FILE.tmp" && mv "$STATE_FILE.tmp" "$STATE_FILE"

echo ""
echo "签到完成！"
jq -r '.accounts | to_entries[] | "  \(.key): \(.value.status) (\(.value.reward // .value.error))"' "$STATE_FILE"
