package com.lanyuanxiaoyao.service.ai.knowledge.service;

import com.lanyuanxiaoyao.service.ai.knowledge.entity.Knowledge;
import com.lanyuanxiaoyao.service.ai.knowledge.entity.vo.SegmentVO;
import io.qdrant.client.ConditionFactory;
import io.qdrant.client.QdrantClient;
import io.qdrant.client.grpc.Points;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.list.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;

/**
 * @author lanyuanxiaoyao
 * @version 20250528
 */
@Service
public class SegmentService {
  private static final Logger logger = LoggerFactory.getLogger(SegmentService.class);

  private final KnowledgeService knowledgeService;
  private final QdrantClient client;

  public SegmentService(KnowledgeService knowledgeService, VectorStore vectorStore) {
    this.knowledgeService = knowledgeService;
    this.client = (QdrantClient) vectorStore.getNativeClient().orElseThrow();
  }

  public ImmutableList<SegmentVO> list(Long id, Long groupId) throws ExecutionException, InterruptedException {
    Knowledge knowledge = knowledgeService.get(id);
    Points.ScrollResponse response = client.scrollAsync(
            Points.ScrollPoints.newBuilder()
                .setCollectionName(String.valueOf(knowledge.getVectorSourceId()))
                .setWithPayload(Points.WithPayloadSelector.newBuilder().setEnable(true).build())
                .setWithVectors(Points.WithVectorsSelector.newBuilder().setEnable(false).build())
                .setFilter(
                    Points.Filter.newBuilder()
                        .addMust(ConditionFactory.matchKeyword("group_id", String.valueOf(groupId)))
                        .build()
                )
                .build()
        )
        .get();
    return response.getResultList()
        .stream()
        .collect(Collectors.toCollection(Lists.mutable::empty))
        .collect(point -> {
          SegmentVO vo = new SegmentVO();
          vo.setId(point.getId().getUuid());
          vo.setText(point.getPayloadMap().get("doc_content").getStringValue());
          return vo;
        })
        .toImmutable();
  }

  public void remove(Long knowledgeId, Long segmentId) throws ExecutionException, InterruptedException {
    Knowledge knowledge = knowledgeService.get(knowledgeId);
    client.deletePayloadAsync(
        String.valueOf(knowledgeId),
        List.of(String.valueOf(segmentId)),
        null,
        null,
        null
    ).get();
  }
}
