package com.infoepoch.pms.agent.domain.care.orchestrator;

import com.alibaba.cloud.ai.graph.RunnableConfig;
import com.alibaba.cloud.ai.graph.agent.ReactAgent;
import com.infoepoch.pms.agent.domain.care.log.CareTraceLogSupport;
import com.infoepoch.pms.agent.domain.care.model.CareQuery;
import com.infoepoch.pms.agent.domain.care.model.CareTaskType;
import com.infoepoch.pms.agent.domain.care.stream.CareStreamingResponseAssembler;
import com.infoepoch.pms.agent.observability.ai.AiObservationSupport;
import com.infoepoch.pms.agent.properties.AiObservabilityProperties;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;

import java.util.Map;

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

@ExtendWith(MockitoExtension.class)
class GeneralConversationExecutorTest {

    @Mock
    private ReactAgent careAgent;

    @Test
    void shouldPassRunnableConfigAndUseFallbackWhenAgentReturnsNoContent() throws Exception {
        GeneralConversationExecutor executor = new GeneralConversationExecutor(
                new CareStreamingResponseAssembler(),
                careAgent,
                new AiObservationSupport(new AiObservabilityProperties(), "pms-agent")
        );
        CareQuery query = new CareQuery(
                CareTaskType.GENERAL_CHAT,
                10,
                false,
                "活动历史有哪些",
                "",
                "活动历史有哪些",
                Map.of(),
                ""
        );
        when(careAgent.stream(anyString(), any(RunnableConfig.class))).thenReturn((Flux) Flux.empty());

        StepVerifier.create(executor.execute("trace-1", "session-1", query))
                .expectNextMatches(chunk -> chunk.contains("你好，我是精准关爱智能体"))
                .verifyComplete();

        ArgumentCaptor<RunnableConfig> configCaptor = ArgumentCaptor.forClass(RunnableConfig.class);
        verify(careAgent).stream(anyString(), configCaptor.capture());
        RunnableConfig runnableConfig = configCaptor.getValue();
        assertEquals("session-1", runnableConfig.threadId().orElseThrow());
        assertEquals("trace-1", runnableConfig.metadata().orElseThrow().get(CareTraceLogSupport.METADATA_TRACE_ID));
        assertEquals("session-1", runnableConfig.metadata().orElseThrow().get(CareTraceLogSupport.METADATA_SESSION_ID));
        assertEquals("通用对话", runnableConfig.metadata().orElseThrow().get(CareTraceLogSupport.METADATA_SCENE));
        assertEquals("trace-1", runnableConfig.metadata().orElseThrow().get("requestId"));
        assertEquals("trace-1", runnableConfig.metadata().orElseThrow().get("flowId"));
    }
}
