package com.infoepoch.pms.agent.platform.chat.domain;

import com.infoepoch.pms.agent.platform.chatbot.domain.Chatbot;
import org.junit.jupiter.api.Test;

import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

class ConversationTest {

    @Test
    void shouldPersistStructuredSnapshotsWhenConversationIsCreated() {
        LocalDateTime now = LocalDateTime.now();
        Chatbot chatbot = Chatbot.restore(
                "chatbot-1",
                "客服助手",
                "desc",
                null,
                null,
                List.of(),
                20,
                true,
                now,
                now,
                Set.of()
        );
        Session session = Session.restore("session-1", "user-1", chatbot, Session.STATUS_ACTIVE, null, now, now);
        Map<String, Object> metadata = new LinkedHashMap<>();
        metadata.put("tokens", 18);
        List<ChatMessageBlock> blocks = List.of(
                new MarkdownBlock("hello"),
                new TraceTimelineBlock(
                        new TraceTimelineBlock.TraceTimelineSummary(1, 0),
                        List.of(new TraceTimelineItem("tool-1", "search", "Search", "finished",
                                "node-1", now, now.plusSeconds(1), "{}", "{\"ok\":true}", null))
                )
        );

        Conversation conversation = new Conversation(
                session,
                "session-1",
                Conversation.ROLE_ASSISTANT,
                "处理完成",
                null,
                metadata,
                blocks
        );

        assertNotNull(conversation.getMetadataJson());
        assertNotNull(conversation.getBlocksJson());
        assertEquals("session-1", conversation.getThreadId());

        Conversation restored = new Conversation(
                conversation.getId(),
                session.getId(),
                conversation.getRole(),
                conversation.getContent(),
                null,
                conversation.getMetadataJson(),
                conversation.getBlocksJson(),
                conversation.getCreatedAt(),
                "session-1"
        );

        assertEquals(18, restored.getMetadata().get("tokens"));
        assertEquals(2, restored.getBlocks().size());
        assertEquals("markdown", restored.getBlocks().get(0).getType());
        assertEquals("trace-timeline", restored.getBlocks().get(1).getType());
        assertEquals("session-1", restored.getThreadId());
    }
}
