package tech.easyflow.admin.service.ai;

import com.easyagents.flow.core.chain.ChainConsts;
import com.easyagents.flow.core.chain.runtime.ChainExecutor;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

/**
 * {@link WorkflowChatEventStream} 最终输出协议测试。
 */
public class WorkflowChatEventStreamTest {

    /**
     * 验证会话事件流不再订阅节点显式输出。
     */
    @Test
    public void shouldOnlyRegisterLifecycleAndErrorListeners() {
        ChainExecutor chainExecutor = mock(ChainExecutor.class);
        WorkflowChatEventStream eventStream =
                new WorkflowChatEventStream(chainExecutor);

        eventStream.registerListeners();

        verify(chainExecutor).addEventListener(any());
        verify(chainExecutor).addErrorListener(any());
        verify(chainExecutor, never()).addOutputListener(any());
    }

    /**
     * 验证顶级工作流最终输出会保留业务结构并移除内部控制字段。
     */
    @Test
    public void shouldKeepStructuredFinalOutputAndRemoveInternalFields() {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("summary", "执行完成");
        result.put("items", List.of(
                Map.of("name", "A", "score", 90),
                Map.of("name", "B", "score", 85)
        ));
        result.put(ChainConsts.CHAIN_STATE_STATUS_KEY, "SUCCEEDED");
        result.put(ChainConsts.CHAIN_STATE_MESSAGE_KEY, "internal");
        result.put(ChainConsts.NODE_STATE_STATUS_KEY, "SUCCESS");
        result.put(ChainConsts.SCHEDULE_NEXT_NODE_DISABLED_KEY, true);

        Map<String, Object> visible =
                WorkflowChatEventStream.visibleFinalOutput(result);

        Assert.assertEquals(visible.get("summary"), "执行完成");
        Assert.assertEquals(visible.get("items"), result.get("items"));
        Assert.assertEquals(visible.size(), 2);
        Assert.assertEquals(result.size(), 6);
    }

    /**
     * 验证空执行结果被规范化为空对象。
     */
    @Test
    public void shouldNormalizeMissingFinalOutputToEmptyMap() {
        Assert.assertTrue(
                WorkflowChatEventStream.visibleFinalOutput(null).isEmpty()
        );
    }
}
