package org.xyzh.ai.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.xyzh.api.ai.knowledge.AiKnowledgeService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.dto.ai.TbAiKnowledge;

import java.util.List;
import java.util.Map;

/**
 * @description AI知识库管理控制器
 * @filename AiKnowledgeController.java
 * @author AI Assistant
 * @copyright xyzh
 * @since 2025-11-04
 */
@Slf4j
@RestController
@RequestMapping("/ai/knowledge")
public class AiKnowledgeController {

    @Autowired
    private AiKnowledgeService knowledgeService;

    /**
     * @description 创建知识库
     * @param knowledge 知识库对象
     * @return ResultDomain<TbAiKnowledge>
     * @author AI Assistant
     * @since 2025-11-04
     */
    @PostMapping
    public ResultDomain<TbAiKnowledge> createKnowledge(@RequestBody TbAiKnowledge knowledge) {
        // 默认权限为PUBLIC（公开）
        String permissionType = "PUBLIC";
        List<String> deptIds = null;
        List<String> roleIds = null;
        
        log.info("创建知识库: name={}", knowledge.getTitle());
        return knowledgeService.createKnowledge(knowledge, permissionType, deptIds, roleIds);
    }

    /**
     * @description 更新知识库
     * @param knowledge 知识库信息
     * @return ResultDomain<TbAiKnowledge>
     * @author AI Assistant
     * @since 2025-11-04
     */
    @PutMapping
    public ResultDomain<TbAiKnowledge> updateKnowledge(@RequestBody TbAiKnowledge knowledge) {
        log.info("更新知识库");
        return knowledgeService.updateKnowledge(knowledge);
    }

    /**
     * @description 删除知识库
     * @param id 知识库ID
     * @return ResultDomain<Boolean>
     * @author AI Assistant
     * @since 2025-11-04
     */
    @DeleteMapping("/{id}")
    public ResultDomain<Boolean> deleteKnowledge(@PathVariable(name = "id") String id) {
        log.info("删除知识库: id={}", id);
        return knowledgeService.deleteKnowledge(id);
    }

    /**
     * @description 根据ID获取知识库
     * @param id 知识库ID
     * @return ResultDomain<TbAiKnowledge>
     * @author AI Assistant
     * @since 2025-11-04
     */
    @GetMapping("/{id}")
    public ResultDomain<TbAiKnowledge> getKnowledge(@PathVariable(name = "id") String id) {
        log.info("获取知识库: id={}", id);
        return knowledgeService.getKnowledgeById(id);
    }

    /**
     * @description 查询知识库列表
     * @param filter 过滤条件
     * @return ResultDomain<TbAiKnowledge>
     * @author AI Assistant
     * @since 2025-11-04
     */
    @PostMapping("/list")
    public ResultDomain<TbAiKnowledge> listKnowledges(
            @RequestBody(required = false) TbAiKnowledge filter) {
        log.info("查询知识库列表");
        return knowledgeService.listKnowledges(filter);
    }

    /**
     * @description 分页查询知识库
     * @param pageRequest 分页请求（包含filter和pageParam）
     * @return PageDomain<TbAiKnowledge>
     * @author AI Assistant
     * @since 2025-11-04
     */
    @PostMapping("/page")
    public ResultDomain<TbAiKnowledge> pageKnowledges(@RequestBody PageRequest<TbAiKnowledge> pageRequest) {
        log.info("分页查询知识库");
        return knowledgeService.pageKnowledges(pageRequest.getFilter(), pageRequest.getPageParam());
    }

    /**
     * @description 同步Dify知识库信息
     * @param id 知识库ID
     * @return ResultDomain<TbAiKnowledge>
     * @author AI Assistant
     * @since 2025-11-04
     */
    @PostMapping("/{id}/sync")
    public ResultDomain<TbAiKnowledge> syncFromDify(@PathVariable(name = "id") String id) {
        log.info("同步Dify知识库信息: id={}", id);
        return knowledgeService.syncFromDify(id);
    }

    /**
     * @description 更新知识库权限
     * @param requestBody 请求体（knowledgeId, permissionType, deptIds, roleIds）
     * @return ResultDomain<Boolean>
     * @author AI Assistant
     * @since 2025-11-04
     */
    @PutMapping("/permission")
    public ResultDomain<Boolean> updatePermission(@RequestBody Map<String, Object> requestBody) {
        String knowledgeId = (String) requestBody.get("knowledgeId");
        String permissionType = (String) requestBody.get("permissionType");
        @SuppressWarnings("unchecked")
        List<String> deptIds = (List<String>) requestBody.get("deptIds");
        @SuppressWarnings("unchecked")
        List<String> roleIds = (List<String>) requestBody.get("roleIds");
        
        log.info("更新知识库权限: knowledgeId={}, permissionType={}", knowledgeId, permissionType);
        return knowledgeService.updateKnowledgePermission(knowledgeId, permissionType, deptIds, roleIds);
    }

    /**
     * @description 检查知识库权限
     * @param knowledgeId 知识库ID
     * @param operationType 操作类型（READ/WRITE/DELETE）
     * @return ResultDomain<Boolean>
     * @author AI Assistant
     * @since 2025-11-04
     */
    @GetMapping("/{knowledgeId}/permission")
    public ResultDomain<Boolean> checkPermission(
            @PathVariable(name = "knowledgeId") String knowledgeId,
            @RequestParam(name = "operationType") String operationType) {
        log.info("检查知识库权限: knowledgeId={}, operationType={}", knowledgeId, operationType);
        return knowledgeService.checkKnowledgePermission(knowledgeId, operationType);
    }

    /**
     * @description 获取知识库统计信息
     * @param id 知识库ID
     * @return ResultDomain<TbAiKnowledge>
     * @author AI Assistant
     * @since 2025-11-04
     */
    @GetMapping("/{id}/stats")
    public ResultDomain<TbAiKnowledge> getKnowledgeStats(@PathVariable(name = "id") String id) {
        log.info("获取知识库统计信息: id={}", id);
        return knowledgeService.getKnowledgeStats(id);
    }

    /**
     * @description 获取可用的嵌入模型列表
     * @return ResultDomain<Map>
     * @author AI Assistant
     * @since 2025-11-06
     */
    @GetMapping("/embedding-models")
    public ResultDomain<Map<String, Object>> getAvailableEmbeddingModels() {
        log.info("获取可用的嵌入模型列表");
        return knowledgeService.getAvailableEmbeddingModels();
    }

    /**
     * @description 获取可用的Rerank模型列表
     * @return ResultDomain<Map>
     * @author AI Assistant
     * @since 2025-11-06
     */
    @GetMapping("/rerank-models")
    public ResultDomain<Map<String, Object>> getAvailableRerankModels() {
        log.info("获取可用的Rerank模型列表");
        return knowledgeService.getAvailableRerankModels();
    }

    /**
     * @description 获取知识库文档列表
     * @param knowledgeId 知识库ID
     * @param page 页码（从1开始，默认1）
     * @param limit 每页数量（默认20）
     * @return ResultDomain<Map>
     * @author AI Assistant
     * @since 2025-11-07
     */
    @GetMapping("/{knowledgeId}/documents")
    public ResultDomain<Map<String, Object>> getDocumentList(
            @PathVariable(name = "knowledgeId") String knowledgeId,
            @RequestParam(required = false, defaultValue = "1", name = "page") Integer page,
            @RequestParam(required = false, defaultValue = "20", name = "limit") Integer limit) {
        log.info("获取文档列表: knowledgeId={}, page={}, limit={}", knowledgeId, page, limit);
        return knowledgeService.getDocumentList(knowledgeId, page, limit);
    }
}
