package com.agent.management.service.impl;

import com.agent.management.service.VectorStoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class VectorStoreServiceImpl implements VectorStoreService {
    private final ObjectProvider<org.springframework.ai.vectorstore.VectorStore> vectorStoreProvider;
    private final EmbeddingBridgeClient embeddingBridgeClient;

    public VectorStoreServiceImpl(ObjectProvider<org.springframework.ai.vectorstore.VectorStore> vectorStoreProvider,
                                  EmbeddingBridgeClient embeddingBridgeClient) {
        this.vectorStoreProvider = vectorStoreProvider;
        this.embeddingBridgeClient = embeddingBridgeClient;
    }

    @Override public List<String> add(List<Document> documents) { log.warn("VectorStoreService.add is deprecated"); return List.of(); }
    @Override public void deleteByIds(List<String> ids) { log.warn("VectorStoreService.deleteByIds is deprecated"); }

    @Override
    public List<Document> similaritySearch(String query, int topK, Double similarityThreshold, String filterExpression) {
        String bridgeFilter = filterExpression == null ? "" : filterExpression.replace("categoryId", "category_id");
        Map<String, Object> response = embeddingBridgeClient.retrieve(query, topK, "hybrid", bridgeFilter);
        if (!(response.get("hits") instanceof List<?> hits)) return List.of();
        List<Document> documents = new ArrayList<>();
        for (Object item : hits) {
            if (!(item instanceof Map<?, ?> hit)) continue;
            double score = hit.get("score") instanceof Number n ? n.doubleValue() : 0.0;
            if (similarityThreshold != null && score < similarityThreshold) continue;
            Map<String, Object> metadata = new LinkedHashMap<>();
            hit.forEach((key, value) -> { if (key != null && value != null) metadata.put(String.valueOf(key), value); });
            metadata.put("distance", score);
            metadata.put("docName", text(hit.get("filename")));
            putIfNotNull(metadata, "documentId", hit.get("document_id"));
            putIfNotNull(metadata, "categoryId", hit.get("category_id"));
            metadata.put("chunkId", text(hit.get("chunk_id")));
            putIfNotNull(metadata, "chunkIndex", hit.get("chunk_idx"));
            documents.add(new Document(text(hit.get("text")), metadata));
        }
        return documents;
    }

    @Override public boolean isAvailable() { return embeddingBridgeClient.health() || vectorStoreProvider.getIfAvailable() != null; }
    private static void putIfNotNull(Map<String, Object> metadata, String key, Object value) { if (value != null) metadata.put(key, value); }
    private static String text(Object value) { return value == null ? "" : String.valueOf(value); }
}
