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

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.infoepoch.pms.agent.properties.AiObservabilityProperties;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ChatModel;

import java.util.stream.Collectors;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;

class AiModelInvokerTest {

    @Test
    void shouldLogReadableModelRequestAndResponse() {
        ChatModel chatModel = Mockito.mock(ChatModel.class);
        when(chatModel.call(anyString())).thenReturn("GENERAL_CHAT");
        AiObservabilityProperties properties = new AiObservabilityProperties();
        properties.setPayloadMode(AiObservabilityProperties.PayloadMode.FULL);
        AiObservationSupport support = new AiObservationSupport(properties, "pms-agent");
        AiObservationLogger logger = new AiObservationLogger(support);
        AiModelInvoker invoker = new AiModelInvoker(logger, support);
        AiObservationContext context = AiObservationContext.builder()
                .traceId("trace-1")
                .requestId("request-1")
                .sessionId("session-1")
                .flowId("flow-1")
                .scene("任务分类")
                .componentType(AiComponentType.MODEL)
                .componentName("intent-classifier")
                .modelProvider("siliconflow")
                .modelName("deepseek")
                .build();
        ListAppender<ILoggingEvent> appender = attachAppender(AiModelInvoker.class);

        String response = invoker.call(context, "用户输入：你好", chatModel);

        assertEquals("GENERAL_CHAT", response);
        String logs = joinedLogs(appender);
        assertTrue(logs.contains("[链路ID=trace-1]"));
        assertTrue(logs.contains("[会话ID=session-1]"));
        assertTrue(logs.contains("[阶段=任务分类模型请求]"));
        assertTrue(logs.contains("[阶段=任务分类模型完整返回]"));
        assertTrue(logs.contains("用户输入：你好"));
        assertTrue(logs.contains("GENERAL_CHAT"));
    }

    private ListAppender<ILoggingEvent> attachAppender(Class<?> loggerClass) {
        Logger logger = (Logger) LoggerFactory.getLogger(loggerClass);
        ListAppender<ILoggingEvent> appender = new ListAppender<>();
        appender.start();
        logger.addAppender(appender);
        return appender;
    }

    private String joinedLogs(ListAppender<ILoggingEvent> appender) {
        return appender.list.stream()
                .map(ILoggingEvent::getFormattedMessage)
                .collect(Collectors.joining("\n"));
    }
}
