

import redis
import json
import pandas as pd
from pathlib import Path

# Redis 配置信息
REDIS_CONFIG = {
    'host': '120.79.147.190',
    'port': 6379,
    'password': 'fG7#vT6kQ1pX',
    'db': 13,
    'decode_responses': True
}

# 连接到 Redis
r = redis.Redis(**REDIS_CONFIG)

def sanitize_sheet_name(name):
    # Excel 不允许的 sheet 名字符
    invalid_chars = ['*', '/', '\\', '?', '[', ']', ':']
    for char in invalid_chars:
        name = name.replace(char, '_')
    return name[:31]  # sheet 名最多支持 31 个字符

# 定义要导出的键前缀
prefixes = [
    # "tk_video_data_test:BlissfulAbodeDecor:order:list",
    # "tk_video_data_test:GiftGroveTrove:order:list",
    # "tk_video_data_test:HeartyGreet:order:list",
    # "tk_video_data_test:LilyRose-sharing:order:list",
    "tk_video_data:Sumind_Home:order:list",
    # "tk_video_data_test:UpliftGiftStore:order:list",
    # "tk_video_data_test:Zhehaostationeryshop:order:list",
    # "tk_video_data_test:positiveLiliya:order:list",
    # "tk_video_data_test:tmxpxiicdh0:order:list"
]

# 创建输出目录
output_dir = Path("../TK_video_data/redis_export")
output_dir.mkdir(exist_ok=True)

for prefix in prefixes:
    keys = r.keys(f"{prefix}")

    excel_file = output_dir / f"{prefix.replace(':', '_')}.xlsx"
    valid_data_found = False

    with pd.ExcelWriter(excel_file, engine='openpyxl') as writer:
        for key in keys:
            key_type = r.type(key)

            try:
                if key_type == 'string':
                    value = r.get(key)
                    try:
                        value = json.loads(value)
                    except json.JSONDecodeError:
                        pass
                    df = pd.DataFrame([value])

                elif key_type == 'list':
                    value = r.lrange(key, 0, -1)
                    df = pd.DataFrame([json.loads(v) for v in value])

                elif key_type == 'set':
                    value = list(r.smembers(key))
                    df = pd.DataFrame(value, columns=[key])

                elif key_type == 'zset':
                    value = r.zrange(key, 0, -1, withscores=True)
                    df = pd.DataFrame(value, columns=[key, 'score'])

                elif key_type == 'hash':
                    value = r.hgetall(key)
                    df = pd.DataFrame([value])

                else:
                    continue  # 忽略未知类型

                # 清洗 sheet 名
                sheet_name = sanitize_sheet_name(key)

                # 如果 sheet 名全是无效字符（比如变成 ''），则跳过
                if not sheet_name or sheet_name.strip('_') == '':
                    print(f"Skipping invalid sheet name: {key}")
                    continue

                # 写入 Excel 的一个 sheet
                df.to_excel(writer, sheet_name=sheet_name, index=False)
                valid_data_found = True

            except Exception as e:
                print(f"Error processing key {key}: {e}")

    if valid_data_found:
        print(f"Data for {prefix} has been exported to Excel: {excel_file}")
    else:
        # 删除空文件
        if excel_file.exists():
            excel_file.unlink()
        print(f"No valid data found for {prefix}, Excel file was not created.")

