#!/usr/bin/env python3
"""一次性修复 id=216 的 merge_forward 记录，重新解析媒体并生成 forward_detail"""
import os
import sys
import json
import subprocess
import logging
import re
import pymysql
from datetime import datetime, timezone, timedelta

logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
log = logging.getLogger(__name__)

# 引入同步脚本的函数（复用 process_merge_forward_message）
sys.path.insert(0, os.path.dirname(__file__))
from sync_group_to_mysql import (
    process_merge_forward_message, CosUploader,
    LARK_CLI_CONFIG, CHAT_ID, CHAT_NAME, WORK_DIR,
    COS_BASE_PATH, TZ
)

MYSQL_HOST = "bj-cdb-8frbdwju.sql.tencentcdb.com"
MYSQL_PORT = 25413
MYSQL_USER = "chatbot"
MYSQL_PASS = "xhuBx7d@uT2gUVv"
MYSQL_DB = "vala_test"
MYSQL_TABLE = "lark_group_message"

TARGET_MSG_ID = "om_x100b50f7871e74a8c39cb1549d9052f"


def fetch_message_by_id(msg_id: str) -> dict:
    """通过 message_id 拉取单条消息"""
    env = os.environ.copy()
    env['LARKSUITE_CLI_CONFIG_DIR'] = LARK_CLI_CONFIG
    # 用一个大时间窗口保证拉到
    cmd = [
        'lark-cli', 'im', '+chat-messages-list',
        '--chat-id', CHAT_ID,
        '--start', '2026-05-07T15:00:00+08:00',
        '--end', '2026-05-07T15:30:00+08:00',
        '--sort', 'asc', '--page-size', '50',
        '--as', 'bot'
    ]
    result = subprocess.run(cmd, capture_output=True, text=True, env=env)
    if result.returncode != 0:
        log.error(f"lark-cli error: {result.stderr}")
        return None
    try:
        data = json.loads(result.stdout)
    except json.JSONDecodeError:
        log.error(f"lark-cli JSON parse error")
        return None

    messages = data.get('data', {}).get('messages', [])
    for m in messages:
        if m.get('message_id') == msg_id:
            return m
    return None


def main():
    os.makedirs(WORK_DIR, exist_ok=True)

    log.info(f"拉取消息: {TARGET_MSG_ID}")
    msg = fetch_message_by_id(TARGET_MSG_ID)
    if not msg:
        log.error("未找到目标消息")
        return

    log.info(f"消息类型: {msg.get('msg_type')}, 发送者: {msg.get('sender', {}).get('name')}")

    cos_uploader = CosUploader()
    date_str = datetime.now(TZ).strftime('%Y-%m-%d')

    log.info("开始处理 merge_forward...")
    record = process_merge_forward_message(msg, cos_uploader, date_str)
    if not record:
        log.error("处理失败")
        return

    log.info(f"处理完成, forward_detail 长度: {len(record.get('forward_detail', ''))}")
    log.info(f"content: {record['content'][:200]}...")

    # 更新数据库
    conn = pymysql.connect(
        host=MYSQL_HOST, port=MYSQL_PORT,
        user=MYSQL_USER, password=MYSQL_PASS,
        database=MYSQL_DB, charset='utf8mb4'
    )
    try:
        with conn.cursor() as cursor:
            sql = f"""
                UPDATE {MYSQL_TABLE}
                SET content = %s, forward_detail = %s
                WHERE message_id = %s
            """
            cursor.execute(sql, (
                record['content'],
                record['forward_detail'],
                TARGET_MSG_ID
            ))
            conn.commit()
            log.info(f"数据库更新成功, affected rows: {cursor.rowcount}")
    except Exception as e:
        log.error(f"数据库更新失败: {e}")
        conn.rollback()
    finally:
        conn.close()

    # 打印 forward_detail 前几行
    log.info("=== forward_detail preview ===")
    for line in record['forward_detail'].split('\n')[:15]:
        print(line)
    print("...")


if __name__ == '__main__':
    main()
