import json
import copy

from datetime import timedelta, datetime

def router_logger(logger_object, request, request_body=None, error=None):
    """
    router 로깅
    
     * 안면인식의 경우 이미지데이터가 너무 커서 길이로 return

    :param logger_object: logger
    :param request: request info
    :param request_body: request body info, defaults to None
    :param error: traceback, defaults to None
    """
    _fr_api_name = "/api/services/AE/FR-Recognize"
    
    time_format = '%Y/%m/%d %H:%M:%S'
    
    request_body_dict = copy.deepcopy(request_body.dict()) if request_body else None
    
    if request.url.path == _fr_api_name:

        # NOTE 타겟이 하나일 경우 기준
        _detect_dict = {
            "id": request_body_dict["targets"]["detect_list"][0]["id"],
            "worker_image": str(len(request_body_dict["targets"]["detect_list"][0]["worker_image"])),
            "target_image": str(len(request_body_dict["targets"]["detect_list"][0]["target_image"]))
        }
        _detect_list = [_detect_dict]
        request_body_dict["targets"]["detect_list"] = _detect_list
        
        
    log_dict = dict(
        api = request.url.path,
        datetimeKST = (datetime.utcnow() + timedelta(hours=9)).strftime(time_format),
        clientIP = request.state.ip,
        request = request_body_dict,
        errorDetail = f"{error.format_exc()}" if error else None
    )
    
    if error :
        logger_object.error(json.dumps(log_dict, ensure_ascii=False))
    else:
        logger_object.info(json.dumps(log_dict, ensure_ascii=False))