import json
import logging
import os

from ylog.context import get_log_context
from ylog.format import QloudJsonFormatter

IS_DEPLOY = 'DEPLOY_BOX_ID' in os.environ


class JsonFormatter(QloudJsonFormatter):
    def format(self, record):
        record.message = record.getMessage()

        log_data = {
            'message': record.message,
            'level': record.levelname,
        }
        if IS_DEPLOY:
            log_data['levelStr'] = record.levelname
            log_data['loggerName'] = record.name
            log_data['level'] = record.levelno

        if record.exc_info:
            exc = logging.Formatter.formatException(self, record.exc_info)
            log_data['stackTrace'] = exc

        fields = {}

        standard_fields = self._get_standard_fields(record)
        if standard_fields:
            standard_fields['orig_msg'] = record.msg
            fields['std'] = standard_fields

        log_context_fields = get_log_context()
        fields['context'] = log_context_fields or {}

        if hasattr(record, 'args') and isinstance(record.args, dict):
            task = {}
            for param_name in ['id', 'name', 'args', 'kwargs']:
                param = record.args.get(param_name)
                if param:
                    task[param_name] = param
            if task:
                fields['context']['celery_task'] = task

        if fields:
            log_data['@fields'] = fields

        log_data['request_id'] = log_context_fields.get('request_id')
        yauid = log_context_fields.get('yauid')
        if yauid:
            log_data['user_id'] = yauid

        return json.dumps(log_data)
