import time
import asyncio
import inspect
from functools import wraps
from foundation.observability.logger.loggering import review_logger as logger

def track_execution_time(func):
    """
    追踪函数执行时间并通过日志输出的装饰器
    同时支持同步和异步函数，记录函数开始执行、执行完成及耗时（保留两位小数）
    """
    @wraps(func)
    def sync_wrapper(*args, **kwargs):
        logger.info(f"[{func.__name__}] 开始执行")
        start_time = time.perf_counter()

        try:
            return func(*args, **kwargs)
        finally:
            duration = time.perf_counter() - start_time
            logger.info(f"[{func.__name__}] 执行完成，耗时: {duration:.2f} 秒")

    @wraps(func)
    async def async_wrapper(*args, **kwargs):
        logger.info(f"[{func.__name__}] 开始执行")
        start_time = time.perf_counter()

        try:
            return await func(*args, **kwargs)
        finally:
            duration = time.perf_counter() - start_time
            logger.info(f"[{func.__name__}] 执行完成，耗时: {duration:.2f} 秒")

    # 检查函数是否是异步函数
    if inspect.iscoroutinefunction(func):
        return async_wrapper
    else:
        return sync_wrapper