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.ai.client.DifyApiClient;
import org.xyzh.ai.mapper.AiUploadFileMapper;
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.dto.ai.TbAiUploadFile;

import com.alibaba.fastjson2.JSONObject;

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

/**
 * @description Dify API代理控制器 - 转发分段管理相关API到Dify
 * @filename DifyProxyController.java
 * @author AI Assistant
 * @copyright xyzh
 * @since 2025-11-04
 */
@Slf4j
@RestController
@RequestMapping("/ai/dify")
public class DifyProxyController {

    @Autowired
    private DifyApiClient difyApiClient;

    @Autowired
    private AiUploadFileMapper uploadFileMapper;



    // ===================== 文档分段管理 API =====================

    /**
     * @description 获取文档分段列表（支持分页）
     * @param datasetId Dify数据集ID
     * @param documentId Dify文档ID
     * @param page 页码（默认1）
     * @param limit 每页条数（默认10）
     * @return ResultDomain<JSONObject> 分段列表JSON（包含分页信息）
     * @author AI Assistant
     * @since 2025-11-04
     */
    @GetMapping("/datasets/{datasetId}/documents/{documentId}/segments")
    public ResultDomain<JSONObject> getDocumentSegments(
            @PathVariable(name = "datasetId") String datasetId,
            @PathVariable(name = "documentId") String documentId,
            @RequestParam(name = "page", defaultValue = "1") int page,
            @RequestParam(name = "limit", defaultValue = "20") int limit) {
        ResultDomain<JSONObject> result = new ResultDomain<>();
        log.info("获取文档分段列表: datasetId={}, documentId={}, page={}, limit={}", 
                datasetId, documentId, page, limit);
        
        try {
            // 调用Dify API（使用默认配置的API Key，支持分页）
            String path = "/datasets/" + datasetId + "/documents/" + documentId + 
                         "/segments?page=" + page + "&limit=" + limit;
            String response = difyApiClient.get(path, null);
            JSONObject jsonObject = JSONObject.parseObject(response);
            
            // 解析数据列表
            List<JSONObject> data = jsonObject.getJSONArray("data").toList(JSONObject.class);
            
            // 构建分页返回对象
            PageDomain<JSONObject> pageDomain = new PageDomain<>();
            pageDomain.setDataList(data);
            
            // 设置分页参数（添加空值检查）
            PageParam pageParam = new PageParam();
            pageParam.setPageSize(limit);
            pageParam.setPageNumber(page);
            
            // 安全地获取 total，如果不存在则使用 data.size()
            Long total = jsonObject.getLong("total");
            pageParam.setTotalElements(total != null ? total : (long) data.size());
            
            // 安全地获取 total_pages，如果不存在则计算
            Integer totalPages = jsonObject.getInteger("total_pages");
            if (totalPages == null) {
                long totalElements = pageParam.getTotalElements();
                totalPages = (int) Math.ceil((double) totalElements / limit);
            }
            pageParam.setTotalPages(totalPages);
            
            pageDomain.setPageParam(pageParam);
            
            // 返回完整的分页数据
            result.success("获取文档分段列表成功", pageDomain);
            return result;
        } catch (Exception e) {
            log.error("获取文档分段列表失败", e);
            result.fail("获取文档分段列表失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * @description 更新文档分段
     * @param datasetId Dify数据集ID
     * @param documentId Dify文档ID
     * @param segmentId 分段ID
     * @param requestBody 请求体（包含segment对象）
     * @return ResultDomain<String> 更新结果
     * @author AI Assistant
     * @since 2025-11-07
     */
    @PostMapping("/datasets/{datasetId}/documents/{documentId}/segments/{segmentId}")
    public ResultDomain<String> updateSegment(
            @PathVariable(name = "datasetId") String datasetId,
            @PathVariable(name = "documentId") String documentId,
            @PathVariable(name = "segmentId") String segmentId,
            @RequestBody Map<String, Object> requestBody) {
        
        log.info("更新文档分段: datasetId={}, documentId={}, segmentId={}", 
                datasetId, documentId, segmentId);
        
        ResultDomain<String> result = new ResultDomain<>();
        try {
            // 调用Dify API（使用默认配置的API Key）
            String path = "/datasets/" + datasetId + "/documents/" + documentId + 
                         "/segments/" + segmentId;
            String response = difyApiClient.post(path, requestBody, null);
            
            result.success("更新分段成功", response);
            return result;
        } catch (Exception e) {
            log.error("更新分段失败", e);
            result.fail("更新分段失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * @description 创建文档分段
     * @param datasetId Dify数据集ID
     * @param documentId Dify文档ID
     * @param requestBody 请求体（包含segments数组）
     * @return ResultDomain<String> 创建结果
     * @author AI Assistant
     * @since 2025-11-07
     */
    @PostMapping("/datasets/{datasetId}/documents/{documentId}/segments")
    public ResultDomain<String> createSegment(
            @PathVariable(name = "datasetId") String datasetId,
            @PathVariable(name = "documentId") String documentId,
            @RequestBody Map<String, Object> requestBody) {
        
        log.info("创建文档分段: datasetId={}, documentId={}", datasetId, documentId);
        
        ResultDomain<String> result = new ResultDomain<>();
        try {
            // 调用Dify API（使用默认配置的API Key）
            String path = "/datasets/" + datasetId + "/documents/" + documentId + "/segments";
            String response = difyApiClient.post(path, requestBody, null);
            int i = uploadFileMapper.chunkSync(documentId, 1);
            if (i>0) {
                result.success("创建分段成功", response);
                return result;
            } else {
                result.fail("创建分段失败: 分段同步失败");
                return result;
            }
        } catch (Exception e) {
            log.error("创建分段失败", e);
            result.fail("创建分段失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * @description 删除文档分段
     * @param datasetId Dify数据集ID
     * @param documentId Dify文档ID
     * @param segmentId 分段ID
     * @return ResultDomain<String> 删除结果
     * @author AI Assistant
     * @since 2025-11-07
     */
    @DeleteMapping("/datasets/{datasetId}/documents/{documentId}/segments/{segmentId}")
    public ResultDomain<String> deleteSegment(
            @PathVariable(name = "datasetId") String datasetId,
            @PathVariable(name = "documentId") String documentId,
            @PathVariable(name = "segmentId") String segmentId) {
        
        log.info("删除文档分段: datasetId={}, documentId={}, segmentId={}", 
                datasetId, documentId, segmentId);
        
        ResultDomain<String> result = new ResultDomain<>();
        try {
            // 调用Dify API（使用默认配置的API Key）
            String path = "/datasets/" + datasetId + "/documents/" + documentId + 
                         "/segments/" + segmentId;
            String response = difyApiClient.delete(path, null);
            int i = uploadFileMapper.chunkSync(documentId, -1);
            if (i>0) {
                result.success("删除分段成功", response);
                return result;
            } else {
                result.fail("删除分段失败: 分段同步失败");
                return result;
            }
        } catch (Exception e) {
            log.error("删除分段失败", e);
            result.fail("删除分段失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * @description 获取分段的子块列表
     * @param datasetId Dify数据集ID
     * @param documentId Dify文档ID
     * @param segmentId 分段ID
     * @return ResultDomain<String> 子块列表JSON
     * @author AI Assistant
     * @since 2025-11-04
     */
    @GetMapping("/datasets/{datasetId}/documents/{documentId}/segments/{segmentId}/child_chunks")
    public ResultDomain<String> getChildChunks(
            @PathVariable(name = "datasetId") String datasetId,
            @PathVariable(name = "documentId") String documentId,
            @PathVariable(name = "segmentId") String segmentId) {
        
        log.info("获取子块列表: datasetId={}, documentId={}, segmentId={}", 
                datasetId, documentId, segmentId);
        
        ResultDomain<String> result = new ResultDomain<>();
        try {
            // 调用Dify API（使用默认配置的API Key）
            String path = "/datasets/" + datasetId + "/documents/" + documentId + 
                         "/segments/" + segmentId + "/child_chunks";
            String response = difyApiClient.get(path, null);
            
            result.success("获取子块列表成功", response);
            return result;
        } catch (Exception e) {
            log.error("获取子块列表失败", e);
            result.fail("获取子块列表失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * @description 更新子块内容
     * @param datasetId Dify数据集ID
     * @param documentId Dify文档ID
     * @param segmentId 分段ID
     * @param childChunkId 子块ID
     * @param requestBody 请求体（包含content等字段）
     * @return ResultDomain<String> 更新后的子块JSON
     * @author AI Assistant
     * @since 2025-11-04
     */
    @PatchMapping("/datasets/{datasetId}/documents/{documentId}/segments/{segmentId}/child_chunks/{childChunkId}")
    public ResultDomain<String> updateChildChunk(
            @PathVariable(name = "datasetId") String datasetId,
            @PathVariable(name = "documentId") String documentId,
            @PathVariable(name = "segmentId") String segmentId,
            @PathVariable(name = "childChunkId") String childChunkId,
            @RequestBody Map<String, Object> requestBody) {
        
        log.info("更新子块: datasetId={}, documentId={}, segmentId={}, childChunkId={}", 
                datasetId, documentId, segmentId, childChunkId);
        
        ResultDomain<String> result = new ResultDomain<>();
        try {
            // 调用Dify API（使用默认配置的API Key）
            String path = "/datasets/" + datasetId + "/documents/" + documentId + 
                         "/segments/" + segmentId + "/child_chunks/" + childChunkId;
            String response = difyApiClient.patch(path, requestBody, null);
            
            result.success("更新子块成功", response);
            return result;
        } catch (Exception e) {
            log.error("更新子块失败", e);
            result.fail("更新子块失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * @description 创建子块
     * @param datasetId Dify数据集ID
     * @param documentId Dify文档ID
     * @param segmentId 分段ID
     * @param requestBody 请求体（包含content等字段）
     * @return ResultDomain<String> 新创建的子块JSON
     * @author AI Assistant
     * @since 2025-11-04
     */
    @PostMapping("/datasets/{datasetId}/documents/{documentId}/segments/{segmentId}/child_chunks")
    public ResultDomain<String> createChildChunk(
            @PathVariable(name = "datasetId") String datasetId,
            @PathVariable(name = "documentId") String documentId,
            @PathVariable(name = "segmentId") String segmentId,
            @RequestBody Map<String, Object> requestBody) {
        
        log.info("创建子块: datasetId={}, documentId={}, segmentId={}", 
                datasetId, documentId, segmentId);
        
        ResultDomain<String> result = new ResultDomain<>();
        try {
            // 调用Dify API（使用默认配置的API Key）
            String path = "/datasets/" + datasetId + "/documents/" + documentId + 
                         "/segments/" + segmentId + "/child_chunks";
            String response = difyApiClient.post(path, requestBody, null);
            
            result.success("创建子块成功", response);
            return result;
        } catch (Exception e) {
            log.error("创建子块失败", e);
            result.fail("创建子块失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * @description 删除子块
     * @param datasetId Dify数据集ID
     * @param documentId Dify文档ID
     * @param segmentId 分段ID
     * @param childChunkId 子块ID
     * @return ResultDomain<String> 删除结果
     * @author AI Assistant
     * @since 2025-11-04
     */
    @DeleteMapping("/datasets/{datasetId}/documents/{documentId}/segments/{segmentId}/child_chunks/{childChunkId}")
    public ResultDomain<String> deleteChildChunk(
            @PathVariable(name = "datasetId") String datasetId,
            @PathVariable(name = "documentId") String documentId,
            @PathVariable(name = "segmentId") String segmentId,
            @PathVariable(name = "childChunkId") String childChunkId) {
        
        log.info("删除子块: datasetId={}, documentId={}, segmentId={}, childChunkId={}", 
                datasetId, documentId, segmentId, childChunkId);
        
        ResultDomain<String> result = new ResultDomain<>();
        try {
            // 调用Dify API（使用默认配置的API Key）
            String path = "/datasets/" + datasetId + "/documents/" + documentId + 
                         "/segments/" + segmentId + "/child_chunks/" + childChunkId;
            String response = difyApiClient.delete(path, null);
            
            result.success("删除子块成功", response);
            return result;
        } catch (Exception e) {
            log.error("删除子块失败", e);
            result.fail("删除子块失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * @description 更新文档启用/禁用状态
     * @param datasetId Dify数据集ID
     * @param action 操作类型（enable/disable/archive/un_archive）
     * @param requestBody 请求体（包含document_ids数组）
     * @return ResultDomain<String> 更新结果
     * @author AI Assistant
     * @since 2025-11-07
     */
    @PostMapping("/datasets/{datasetId}/documents/status/{action}")
    public ResultDomain<String> updateDocumentStatus(
            @PathVariable(name = "datasetId") String datasetId,
            @PathVariable(name = "action") String action,
            @RequestBody Map<String, Object> requestBody) {
        
        log.info("更新文档状态: datasetId={}, action={}, documentIds={}", 
                datasetId, action, requestBody.get("document_ids"));
        
        ResultDomain<String> result = new ResultDomain<>();
        try {
            // 1. 调用Dify API（使用默认配置的API Key）
            String path = "/datasets/" + datasetId + "/documents/status/" + action;
            String response = difyApiClient.patch(path, requestBody, null);
            
            // 2. 同步更新本地数据库
            @SuppressWarnings("unchecked")
            List<String> documentIds = (List<String>) requestBody.get("document_ids");
            if (documentIds != null && !documentIds.isEmpty()) {
                Boolean enabled = null;
                if ("enable".equals(action)) {
                    enabled = true;
                } else if ("disable".equals(action)) {
                    enabled = false;
                }
                
                if (enabled != null) {
                    for (String documentId : documentIds) {
                        try {
                            TbAiUploadFile file = uploadFileMapper.selectFileByDifyDocumentId(documentId);
                            if (file != null) {
                                file.setEnabled(enabled);
                                file.setUpdateTime(new Date());
                                uploadFileMapper.updateUploadFile(file);
                                log.info("本地数据库更新成功: documentId={}, enabled={}", documentId, enabled);
                            }
                        } catch (Exception e) {
                            log.warn("更新本地数据库失败: documentId={}, error={}", documentId, e.getMessage());
                        }
                    }
                }
            }
            
            result.success("更新文档状态成功", response);
            return result;
        } catch (Exception e) {
            log.error("更新文档状态失败", e);
            result.fail("更新文档状态失败: " + e.getMessage());
            return result;
        }
    }
}

