"""
收支记录定时任务：每日清零各俱乐部今日流水/今日支出。
"""
from celery import shared_task
from datetime import datetime
import logging

from jituan.services.szjilu_accounting import reset_all_daily_szjilu
from utils.celery_utils import log_task_execution, rollback_on_failure

logger = logging.getLogger(__name__)


@shared_task
@rollback_on_failure("收支记录每日清零")
def daily_sz_reset_task():
    """收支记录每日清零 - 每天凌晨0点5分执行。"""
    try:
        today = datetime.now().strftime('%Y-%m-%d')
        logger.info(f"开始执行收支记录清零任务，日期: {today}")

        updated = reset_all_daily_szjilu()
        result_msg = f"收支记录清零完成 - 日期: {today}, 俱乐部记录数: {updated}"
        log_task_execution("收支记录每日清零", True, result_msg)

        return {
            "success": True,
            "date": today,
            "clubs_updated": updated,
            "message": result_msg,
        }

    except Exception as e:
        error_msg = f"收支记录每日清零失败: {str(e)}"
        logger.error(error_msg)
        log_task_execution("收支记录每日清零", False, error_msg)

        return {
            "success": False,
            "error": str(e),
            "date": datetime.now().strftime('%Y-%m-%d'),
            "message": error_msg,
        }