package com.infoepoch.pms.agent.observability.ai;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.Map;

/**
 * AI 观测日志输出器。
 */
public class AiObservationLogger {

    private final AiObservationSupport support;

    public AiObservationLogger(AiObservationSupport support) {
        this.support = support;
    }

    public void info(Class<?> source, String message, AiObservationContext context, Map<String, ?> fields) {
        log(source, message, context, fields, null);
    }

    public void error(Class<?> source, String message, AiObservationContext context, Map<String, ?> fields, Throwable error) {
        log(source, message, context, fields, error);
    }

    private void log(Class<?> source, String message, AiObservationContext context, Map<String, ?> fields, Throwable error) {
        if (!support.isEnabled()) {
            return;
        }
        Logger logger = LoggerFactory.getLogger(source);
        support.withObservationContext(context, () -> {
            applyFields(fields);
            try {
                if (error == null) {
                    logger.info(message);
                } else {
                    logger.error(message, error);
                }
                return null;
            } finally {
                clearFields(fields);
            }
        });
    }

    private void applyFields(Map<String, ?> fields) {
        if (fields == null || fields.isEmpty()) {
            return;
        }
        fields.forEach((key, value) -> {
            if (key != null && value != null) {
                MDC.put(key, value.toString());
            }
        });
    }

    private void clearFields(Map<String, ?> fields) {
        if (fields == null || fields.isEmpty()) {
            return;
        }
        fields.keySet().forEach(MDC::remove);
    }
}
