# ！/usr/bin/ python
# -*- coding: utf-8 -*-
'''
@Project    : lq-agent-api
@File       :common.py
@IDE        :PyCharm
@Author     :
@Date       :2025/7/11 11:36
'''
import time
import uuid
from functools import wraps


def return_json(code=0, msg='ok', business_scene=None, data=None, trace_id=str(uuid.uuid4()), data_type="text", page=0, page_size=10, *args, **kwargs):
    res = {
        "code": code,
        "message": msg,
        "page": page,
        "page_size": page_size,
        "trace_id": trace_id,
        "business_scene": business_scene,
    }
    if data:
        if args:
            data += args
        data['dataType'] = data_type
    res['data'] = data

    if kwargs:
        res.update(kwargs)
    return res


def calcu_run_time(logger, name: str):
    """
    执行时间统计装饰器
    :param logger: log obj
    :param name: log name
    :return:
    """

    def inner_fuc(func):
        @wraps(func)
        def calcu_wrapper(*args, **kwargs):
            start_time = float("%.3f" % time.time())
            logger.info(f"{name}_start_time: {start_time}")
            result = func(*args, **kwargs)
            end_time = float("%.3f" % time.time())
            logger.info(f"{name}_end_time: {end_time}")
            logger.info("request_total_cost_time: {}".format(end_time - start_time))
            return result

        return calcu_wrapper

    return inner_fuc



def handler_err(logger, err, trace_id: str="", err_name: str=""):
    """
    日志格式化
    返回具体错误
    报错文件
    报错行数
    :param logger: log obj
    :param err: error obj
    :param operate_id: 操作id, default=""
    :param err_name: error name, default=""
    """
    trace_id = trace_id if trace_id else f"{uuid.uuid4()}"
    logger.error(trace_id=trace_id, log_type=err_name, msg=f'error file: {err}')
    logger.error(trace_id=trace_id, log_type=err_name, msg=f'data error file: {err.__traceback__.tb_frame.f_globals["__file__"]}')
    logger.error(trace_id=trace_id, log_type=err_name, msg=f"data error line: {err.__traceback__.tb_lineno}")
    logger.exception(trace_id=trace_id, log_type=err_name, msg=f"Error Stack trace:")

