if [ "$(id -u)" -ne 0 ]; then
    echo -e "\033[1;31m错误：请使用 sudo 运行本脚本或切换到 root 用户！\033[0m" >&2
    exit 1
fi

RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
PURPLE='\033[1;35m'
NC='\033[0m'

APP_IDS="wxa00ff5f4eb7bc7b2 wxa696fdfb8ff19140 wxbbb3ab1311b6e5ae wx8299365145360ced wx4a7d69061f942625 wxc33157b1f8b00e57 wx18e3c09e013ff9ce wxdf0a6edcd1896a1f"
APP_NAMES="天庭阙电竞 抗压电竞 南波万 星火电竞 科绘 银蛇 三元 探宇"

TARGET_DIR="/data/user/0/com.tencent.mm/files/mmkv/"
echo -e "${BLUE}正在搜索小程序存储文件...${NC}"
FOUND=0

declare -A APP_MAP
ids_arr=($APP_IDS)
names_arr=($APP_NAMES)
for i in "${!ids_arr[@]}"; do
    APP_MAP[${ids_arr[$i]}]=${names_arr[$i]}
done

echo -e "${YELLOW}==================================${NC}"
echo -e "${GREEN}        小程序Token提取工具        ${NC}"
echo -e "${YELLOW}==================================${NC}"
echo -e "请选择操作模式："
echo -e "1. ${GREEN}提取Token${NC}（适用于获取登录凭证）"
echo -e "2. ${RED}删除小程序存储文件${NC}（清除旧Token后需重新登录）"
echo -e "${YELLOW}----------------------------------${NC}"
read -p "请输入选项 [1-2] (默认1): " MODE
MODE=${MODE:-1}

if [[ ! $MODE =~ ^[1-2]$ ]]; then
    echo -e "${RED}错误：无效的选择！${NC}" >&2
    exit 1
fi

FILES=()
while IFS= read -r -d '' TARGET_FILE; do
    [[ "$TARGET_FILE" == *.crc ]] && continue
    FOUND=1
    FILES+=("$TARGET_FILE")
done < <(find "$TARGET_DIR" -name "AppBrandMMKVStorage*" -type f -print0 2>/dev/null)

if [ "$FOUND" -eq 0 ]; then
    echo -e "${RED}错误：未找到小程序存储文件${NC}" >&2
    exit 1
fi

extract_tokens() {
    for TARGET_FILE in "${FILES[@]}"; do
        echo -e "\n${YELLOW}==================================${NC}"
        echo -e "${PURPLE}正在处理文件: $TARGET_FILE${NC}"
        echo -e "${YELLOW}----------------------------------${NC}"
        
        strings "$TARGET_FILE" | grep -a -m1 -oE 'wx8299365145360ced__accessTokenSRString#[0-9]+#[a-fA-F0-9]+' | \
        awk -F# '{printf "\033[1;34m【星火电竞】\033[1;32mToken: %s\033[0m\n", $3}'

        strings "$TARGET_FILE" | grep -a -m1 -oE 'wxdf0a6edcd1896a1f__accessTokenSRString#[0-9]+#[a-fA-F0-9]+' | \
        awk -F# '{printf "\033[1;34m【探宇电竞】\033[1;32mToken: %s\033[0m\n", $3}'

        strings "$TARGET_FILE" | grep -a -m1 -oE 'wx4a7d69061f942625__khdj_thug_tokenKJString#[0-9]+#[a-fA-F0-9]+' | \
        awk -F# '{printf "\033[1;34m【科绘】\033[1;32mToken: %s\033[0m\n", $3}'
        
        strings "$TARGET_FILE" | grep -a -oE 'wx[a-zA-Z0-9]{16}__[^:]+String#[0-9]+#\{[^}]*"value":"[^"]*' | \
        while read -r line; do
            app_id=$(echo "$line" | grep -oE 'wx[a-zA-Z0-9]{16}')
            token=$(echo "$line" | grep -o '"value":"[^"]*' | cut -d'"' -f4)
            if [[ -n "${APP_MAP[$app_id]}" ]]; then
                echo -e "\033[1;34m【${APP_MAP[$app_id]}】\033[1;32mToken: $token\033[0m"
            fi
        done
        
        strings "$TARGET_FILE" | grep -a -oE 'wxbbb3ab1311b6e5ae__token/\.String#[0-9]+#[a-f0-9\-]{36}' | \
        awk -F# '{printf "\033[1;34m【南波万】\033[1;32mToken: %s\033[0m\n", $3}'
    done
}

if [ "$MODE" -eq 1 ]; then
    extract_tokens
    echo -e "\n${YELLOW}==================================${NC}"
    echo -e "${GREEN}所有文件处理完成${NC}"
    echo -e "${RED}注意：${NC}如果获取到多个Token，请："
    echo -e "使用${YELLOW}选项2${NC}删除文件后重新登录"
    echo -e "${YELLOW}==================================${NC}"

elif [ "$MODE" -eq 2 ]; then
    echo -e "${RED}⚠️ 找到以下缓存文件：${NC}"
    printf "  %s\n" "${FILES[@]}"
    echo -e "${YELLOW}----------------------------------${NC}"
    echo -e "${RED}警告：删除后将导致小程序重新登录${NC}"
    read -p "确认要删除以上文件吗？(输入y确认): " CONFIRM
    if [[ "$CONFIRM" == "y" ]]; then
        for file in "${FILES[@]}"; do
            rm -f "$file" && echo -e "${GREEN}✓ 已删除: $file${NC}"
            crc_file="${file}.crc"
            [ -f "$crc_file" ] && rm -f "$crc_file" && echo -e "${GREEN}✓ 已删除: $crc_file${NC}"
        done
        echo -e "${YELLOW}----------------------------------${NC}"
        echo -e "${GREEN}操作完成! 请："
        echo -e "重新登录小程序获取新Token${NC}"
    else
        echo -e "${YELLOW}操作已取消${NC}"
    fi
fi