package org.dromara.knowledge.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.dromara.knowledge.domain.bo.KnowledgeVectorBo;
import org.dromara.knowledge.domain.vo.KnowledgeVectorVo;
import org.dromara.knowledge.service.KnowledgeVectorService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 知识库向量控制器
 *
 * @author pengles
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/knowledge/vector")
public class KnowledgeVectorController extends BaseController {

    private final KnowledgeVectorService knowledgeVectorService;
    private final org.dromara.knowledge.vectorstore.VectorStoreManager vectorStoreManager;

    @PostMapping("/generate")
    @Log(title = "向量生成", businessType = BusinessType.OTHER)
    public R<List<String>> generate(@RequestParam String knowledgeId,
                                    @RequestParam String docId,
                                    @RequestBody List<org.dromara.knowledge.domain.vo.KnowledgeFragmentVo> fragments,
                                    @RequestParam(defaultValue = "bge-large-zh") String model) {
        java.util.Map<String, String> map = new java.util.HashMap<>();
        for (var f : fragments) {
            map.put(f.getFid(), f.getContent());
        }
        List<String> ids = knowledgeVectorService.batchGenerateVectors(knowledgeId, docId, map, model);
        return R.ok(ids);
    }

    @PostMapping("/search")
    @Log(title = "向量检索", businessType = BusinessType.OTHER)
    public R<List<org.dromara.knowledge.domain.vo.KnowledgeSearchResultVo>> search(@RequestParam String knowledgeId,
                                                                                   @RequestParam String query,
                                                                                   @RequestParam(defaultValue = "bge-large-zh") String model,
                                                                                   @RequestParam(defaultValue = "5") Integer topK,
                                                                                   @RequestParam(defaultValue = "0.5") Double threshold,
                                                                                   @RequestParam(defaultValue = "false") boolean distinctByDoc) {
        var res = knowledgeVectorService.vectorSimilaritySearch(knowledgeId, query, model, topK, threshold);
        if (distinctByDoc) {
            java.util.Set<String> seen = new java.util.HashSet<>();
            res = res.stream().filter(r -> {
                if (seen.contains(r.getDocId())) return false;
                seen.add(r.getDocId());
                return true;
            }).toList();
        }
        return R.ok(res);
    }

    @GetMapping("/stats/{knowledgeId}")
    @Log(title = "向量统计", businessType = BusinessType.OTHER)
    public R<java.util.Map<String, Object>> stats(@PathVariable String knowledgeId) {
        return R.ok(knowledgeVectorService.getVectorStatistics(knowledgeId));
    }

    @PostMapping("/rebuild/{knowledgeId}")
    @Log(title = "重建向量索引", businessType = BusinessType.OTHER)
    public R<Void> rebuild(@PathVariable String knowledgeId) {
        vectorStoreManager.current().rebuildIndex(knowledgeId);
        return R.ok();
    }

    @PostMapping("/vectorize-doc")
    @Log(title = "文档批量向量化", businessType = BusinessType.OTHER)
    public R<java.util.List<String>> vectorizeDoc(@RequestParam String knowledgeId,
                                                  @RequestParam String docId,
                                                  @RequestParam(defaultValue = "bge-large-zh") String model) {
        java.util.List<org.dromara.knowledge.domain.vo.KnowledgeFragmentVo> fragments =
                org.dromara.common.core.utils.SpringUtils.getBean(org.dromara.knowledge.service.KnowledgeFragmentService.class)
                        .queryListByDocId(docId);
        java.util.Map<String, String> map = new java.util.HashMap<>();
        for (var f : fragments) map.put(f.getFid(), f.getContent());
        java.util.List<String> ids = knowledgeVectorService.batchGenerateVectors(knowledgeId, docId, map, model);
        return R.ok(ids);
    }

    /**
     * 查询知识库向量列表
     */
    @SaCheckPermission("knowledge:vector:list")
    @GetMapping("/list")
    public TableDataInfo<KnowledgeVectorVo> list(KnowledgeVectorBo bo, PageQuery pageQuery) {
        return knowledgeVectorService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出知识库向量列表
     */
    @SaCheckPermission("knowledge:vector:export")
    @Log(title = "知识库向量", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(KnowledgeVectorBo bo, HttpServletResponse response) {
        List<KnowledgeVectorVo> list = knowledgeVectorService.queryList(bo);
        ExcelUtil.exportExcel(list, "知识库向量", KnowledgeVectorVo.class, response);
    }

    /**
     * 获取知识库向量详细信息
     *
     * @param vectorId 向量ID
     */
    @SaCheckPermission("knowledge:vector:query")
    @GetMapping("/{vectorId}")
    public R<KnowledgeVectorVo> getInfo(@PathVariable Long vectorId) {
        return R.ok(knowledgeVectorService.queryById(vectorId));
    }

    /**
     * 新增知识库向量
     */
    @SaCheckPermission("knowledge:vector:add")
    @Log(title = "知识库向量", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add(@Validated @RequestBody KnowledgeVectorBo bo) {
        return toAjax(knowledgeVectorService.insertByBo(bo));
    }

    /**
     * 修改知识库向量
     */
    @SaCheckPermission("knowledge:vector:edit")
    @Log(title = "知识库向量", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> edit(@Validated @RequestBody KnowledgeVectorBo bo) {
        return toAjax(knowledgeVectorService.updateByBo(bo));
    }

    /**
     * 删除知识库向量
     *
     * @param vectorIds 向量ID数组
     */
    @SaCheckPermission("knowledge:vector:remove")
    @Log(title = "知识库向量", businessType = BusinessType.DELETE)
    @DeleteMapping("/{vectorIds}")
    public R<Void> remove(@PathVariable Long[] vectorIds) {
        return toAjax(knowledgeVectorService.deleteWithValidByIds(List.of(vectorIds), true));
    }

    /**
     * 根据片段ID查询向量列表
     *
     * @param fragmentId 片段ID
     */
    @SaCheckPermission("knowledge:vector:query")
    @GetMapping("/fragment/{fragmentId}")
    public R<List<KnowledgeVectorVo>> getByFragmentId(@PathVariable String fragmentId) {
        return R.ok(knowledgeVectorService.queryByFragmentId(fragmentId));
    }

    /**
     * 根据知识库ID查询向量列表
     *
     * @param knowledgeId 知识库ID
     */
    @SaCheckPermission("knowledge:vector:query")
    @GetMapping("/knowledge/{knowledgeId}")
    public R<List<KnowledgeVectorVo>> getByKnowledgeId(@PathVariable String knowledgeId) {
        return R.ok(knowledgeVectorService.queryByKnowledgeId(knowledgeId));
    }
}
