import json
import os
from functools import wraps
from loguru import logger
from flask import  jsonify
LOG_DIR = "logs"
os.makedirs(LOG_DIR, exist_ok=True)


logger.remove()

logger.add(
    os.path.join(LOG_DIR, "info_{time:YYYY-MM-DD}.log"),
    level="INFO",
    rotation="00:00",
    retention="7 days",
    encoding="utf-8",
    enqueue=True,
    backtrace=False
)

# 配置ERROR级别日志 - 每日滚动，保留7天
logger.add(
    os.path.join(LOG_DIR, "err_{time:YYYY-MM-DD}.log"),
    level="ERROR",
    rotation="00:00",
    retention="7 days",
    encoding="utf-8",
    enqueue=True,
    backtrace=True,
    diagnose=True
)

class ApiResponse:
    @staticmethod
    def success(data=None, msg="success"):
        response = {
            "code": 200,
            "data": data,
            "msg": msg
        }
        logger.info(f"dso-ai-bot: {msg}, 数据: {data}")
        return jsonify(response)

    @staticmethod
    def error(msg="服务器内部错误", code=500):
        response = {
            "code": code,
            "data": None,
            "msg": msg
        }
        logger.error(f"dso-ai-bot: {code}, exception: {msg}")
        return jsonify(response)

def handle_exceptions(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            result = func(*args, **kwargs)
            return ApiResponse.success(result)
        except Exception as e:
            logger.exception(f"function {func.__name__} exception")
            return ApiResponse.error(str(e), 500)
    return wrapper

