package tech.easyflow.ai.easyagentsflow.knowledge;

import com.easyagents.core.document.Document;
import com.easyagents.flow.core.knowledge.Knowledge;
import com.easyagents.flow.core.node.KnowledgeNode;
import org.junit.Assert;
import org.junit.Test;
import tech.easyflow.ai.rag.KnowledgeRetrievalRequest;
import tech.easyflow.ai.service.DocumentCollectionService;

import java.lang.reflect.Field;
import java.math.BigInteger;
import java.util.Collections;
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.when;

/**
 * {@link KnowledgeProviderImpl} 的工作流文档契约测试。
 */
public class KnowledgeProviderImplTest {

    /**
     * 验证对象数组同时提供稳定顶层字段和旧版字段。
     *
     * @throws Exception 注入测试依赖失败时抛出
     */
    @Test
    public void shouldExposeStableDocumentFieldsAndKeepLegacyFields()
            throws Exception {
        Document document = new Document();
        document.setId(BigInteger.valueOf(42));
        document.setTitle("文档标题");
        document.setContent("文档内容");
        document.addMetadata("documentId", BigInteger.valueOf(420));
        document.addMetadata("legacyKey", "legacy-value");

        DocumentCollectionService service =
                mock(DocumentCollectionService.class);
        when(service.search(any(KnowledgeRetrievalRequest.class)))
                .thenReturn(Collections.singletonList(document));
        KnowledgeProviderImpl provider = new KnowledgeProviderImpl();
        setField(provider, "documentCollectionService", service);

        KnowledgeNode knowledgeNode = new KnowledgeNode();
        knowledgeNode.setId("knowledge-node");
        Knowledge knowledge =
                provider.getKnowledge(BigInteger.valueOf(88));
        List<Map<String, Object>> result =
                knowledge.search("问题", 10, knowledgeNode, null);

        Assert.assertEquals(1, result.size());
        Map<String, Object> item = result.get(0);
        Assert.assertEquals("文档标题", item.get("title"));
        Assert.assertEquals("文档内容", item.get("content"));
        Assert.assertEquals(BigInteger.valueOf(420), item.get("documentId"));
        Assert.assertEquals(BigInteger.valueOf(88), item.get("knowledgeId"));
        Assert.assertEquals(42L, ((Number) item.get("id")).longValue());
        Assert.assertTrue(item.containsKey("metadataMap"));
        Assert.assertEquals(
                "legacy-value",
                ((Map<?, ?>) item.get("metadataMap")).get("legacyKey"));
    }

    /**
     * 注入测试依赖。
     *
     * @param target 目标对象
     * @param fieldName 字段名称
     * @param value 字段值
     * @throws Exception 字段不存在或不可访问时抛出
     */
    private static void setField(
            Object target, String fieldName, Object value) throws Exception {
        Field field = KnowledgeProviderImpl.class
                .getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(target, value);
    }
}
