#!/bin/bash

# ==========================================
# Jiaotu Account Pool Sorter v1.0
# ==========================================

ACCOUNTS_FILE="./accounts.txt"
BACKUP_FILE="./accounts.txt.bak"
TEMP_RESULT="./.accounts_temp_sort"

# --- 颜色定义 ---
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

log_info() { echo -e "${GREEN}[INFO] $1${NC}"; }
log_warn() { echo -e "${YELLOW}[WARN] $1${NC}"; }
log_err()  { echo -e "${RED}[ERROR] $1${NC}"; }
log_step() { echo -e "${CYAN}=== $1 ===${NC}"; }

# --- 积分查询函数 (复用核心逻辑) ---
get_points() {
    local C_TOKEN="$1"
    local C_SESSION="$2"
    
    # 清洗数据
    C_TOKEN=$(echo "$C_TOKEN" | tr -d '\r\n ')
    C_SESSION=$(echo "$C_SESSION" | tr -d '\r\n ')

    # 1. 签到 (触发可能的刷新)
    curl -s 'https://api.jiaotuai.cn/api/v1/sign/check' \
      -H "Authorization: Bearer ${C_TOKEN}" \
      -H 'Content-Type: application/json' \
      -H 'User-Agent: Mozilla/5.0' -o /dev/null

    # 2. 查询
    local RESP=$(curl -s 'https://api.jiaotuai.cn/api/v1/product/queryPackageCount' \
      -H "Authorization: Bearer ${C_TOKEN}" \
      -H 'Content-Type: application/json' \
      -H 'User-Agent: Mozilla/5.0' \
      -H "Referer: https://www.jiaotuai.cn/studio?sessionId=${C_SESSION}")

    # 提取 availableCount
    local AVAIL=$(echo "$RESP" | grep -oE '"availableCount":[0-9]+' | grep -oE '[0-9]+' | head -n 1)
    
    # 如果提取失败或为空，默认为 -1 (表示无效账号)
    echo "${AVAIL:--1}"
}

main() {
    # 1. 检查文件
    if [[ ! -f "$ACCOUNTS_FILE" ]]; then
        log_err "未找到文件: $ACCOUNTS_FILE"
        exit 1
    fi

    log_step "Step 1: 备份原始文件"
    cp "$ACCOUNTS_FILE" "$BACKUP_FILE"
    log_info "已备份至: $BACKUP_FILE"

    log_step "Step 2: 正在检查并统计积分..."
    
    # 清空临时文件
    > "$TEMP_RESULT"

    local COUNT=0
    local TOTAL_LINES=$(grep -cve '^\s*$' "$ACCOUNTS_FILE") # 统计非空行
    
    # 读取文件 (使用 fd 3 避免 ssh/curl 冲突)
    while read -r line <&3 || [[ -n "$line" ]]; do
        # 跳过空行和注释
        [[ -z "$line" || "$line" == \#* ]] && continue
        
        ((COUNT++))
        
        # 提取并清洗
        local TOKEN=$(echo "$line" | awk '{print $1}' | tr -d '\r')
        local SESSION=$(echo "$line" | awk '{print $2}' | tr -d '\r')
        
        if [[ -z "$TOKEN" || -z "$SESSION" ]]; then continue; fi

        # 获取积分
        printf "Checking Account %02d/%02d... " "$COUNT" "$TOTAL_LINES"
        local POINTS=$(get_points "$TOKEN" "$SESSION")

        if [[ "$POINTS" -ge 0 ]]; then
            if [[ "$POINTS" -ge 10 ]]; then
                echo -e "${GREEN}积分: ${POINTS}${NC}"
            else
                echo -e "${YELLOW}积分: ${POINTS}${NC}"
            fi
            # 格式: 积分 TOKEN SESSION
            echo "$POINTS $TOKEN $SESSION" >> "$TEMP_RESULT"
        else
            echo -e "${RED}无效/过期${NC}"
            # 无效账号标记为 -1，排在最后
            echo "-1 $TOKEN $SESSION" >> "$TEMP_RESULT"
        fi

    done 3< "$ACCOUNTS_FILE"

    log_step "Step 3: 重新排序 (积分从高到低)"
    
    # 使用 sort 命令排序
    # -k1,1nr : 按照第一列(积分)进行 数值(n) 逆序(r) 排序
    sort -k1,1nr "$TEMP_RESULT" > "${TEMP_RESULT}.sorted"

    log_step "Step 4: 更新账号池"
    
    # 将排序后的结果写回原文件 (去掉第一列积分，只保留 Token 和 Session)
    awk '{print $2, $3}' "${TEMP_RESULT}.sorted" > "$ACCOUNTS_FILE"

    echo "------------------------------------------------"
    echo -e "账号池已更新完毕！"
    echo -e "Top 3 账号状态:"
    head -n 3 "${TEMP_RESULT}.sorted" | awk '{printf "Points: %-4s | ...%s\n", $1, substr($2, length($2)-10, 10)}'
    echo "------------------------------------------------"
    
    # 清理临时文件
    rm -f "$TEMP_RESULT" "${TEMP_RESULT}.sorted"
    log_info "完成。现在您可以运行主脚本了。"
}

# 执行主函数
main
