#!/usr/bin/env python3
"""第二步：查询 parent_address 并合并生成最终 Excel"""
import csv
import os
import sys

# 配置
DB_WELFARE_OUTPUT = '/root/.openclaw/workspace/output/welfare_step1_result.txt'
FINAL_OUTPUT = '/root/.openclaw/workspace/output/福利品用户名单.xlsx'

# 读取第一步结果
orders = []
with open(DB_WELFARE_OUTPUT, 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        orders.append(row)

print(f"读取订单数: {len(orders)}")

# 获取所有 account_id
account_ids = sorted(set(row['用户ID'] for row in orders))
print(f"唯一用户数: {len(account_ids)}")

# 情况分布统计
from collections import Counter
case_dist = Counter(row['来源情况'] for row in orders)
print("\n=== 情况分布（按订单行数）===")
for k, v in case_dist.most_common():
    print(f"  {k}: {v}")

# 检查重复 trade_no
trade_nos = [row['交易号'] for row in orders]
trade_dup = [t for t, c in Counter(trade_nos).items() if c > 1]
if trade_dup:
    print(f"\n⚠️ 重复 trade_no: {trade_dup}")
else:
    print("\n✅ 无重复 trade_no")

# 生成 account_id 列表用于第二步查询
ids_str = ','.join(account_ids)
print(f"\n准备查询 parent_address，共 {len(account_ids)} 个用户")
print(f"account_id 列表已保存")

# 保存 account_ids 供 psql 使用
with open('/root/.openclaw/workspace/output/welfare_account_ids.txt', 'w') as f:
    for aid in account_ids:
        f.write(f"{aid}\n")

print("Done.")
