#!/usr/bin/env python3
"""导出6月份微信反馈数据到 CSV"""
import pymysql, csv

conn = pymysql.connect(
    host='bj-cdb-8frbdwju.sql.tencentcdb.com',
    port=25413,
    user='chatbot',
    password='xhuBx7d@uT2gUVv',
    database='vala_test',
    charset='utf8mb4'
)

cursor = conn.cursor()
cursor.execute("""
    SELECT 
        id, sender_name, msg_type, content, msg_time, svr_msg_id, refer_msg_svrid
    FROM wechat_group_message 
    WHERE msg_time >= '2026-06-01' AND msg_time < '2026-07-01'
    ORDER BY msg_time ASC
""")
rows = cursor.fetchall()
cursor.close()
conn.close()

output_path = '/root/.openclaw/workspace-xiaokui/output/微信反馈_2026年6月.csv'
with open(output_path, 'w', newline='', encoding='utf-8-sig') as f:
    writer = csv.writer(f)
    writer.writerow(['id', 'sender_name', 'msg_type', 'content', 'msg_time', 'svr_msg_id', 'refer_msg_svrid'])
    for row in rows:
        # Replace newlines in content to keep one row per record
        content = (row[3] or '').replace('\n', ' ').replace('\r', ' ')
        writer.writerow([row[0], row[1], row[2], content, str(row[4]), str(row[5]) if row[5] else '', str(row[6]) if row[6] else ''])

print(f"共 {len(rows)} 条记录，已保存到 {output_path}")
