package org.xyzh.ai.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.xyzh.ai.client.DifyApiClient;
import org.xyzh.api.ai.service.DifyProxyService;
import org.xyzh.common.core.domain.ResultDomain;

import java.util.Map;

/**
 * @description Dify代理服务实现（直接转发请求到Dify API）
 * @filename DifyProxyServiceImpl.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-12-17
 */
@DubboService(version="1.0.0", group="ai", timeout=3000, retries=0)
public class DifyProxyServiceImpl implements DifyProxyService {
    private static final Logger logger = LoggerFactory.getLogger(DifyProxyServiceImpl.class);

    @Autowired
    private DifyApiClient difyApiClient;

    @Override
    public ResultDomain<JSONObject> getDocumentSegments(String datasetId, String documentId) {
        // 1. 参数校验
        if (!StringUtils.hasText(datasetId)) {
            return ResultDomain.failure("数据集ID不能为空");
        }
        if (!StringUtils.hasText(documentId)) {
            return ResultDomain.failure("文档ID不能为空");
        }

        try {
            // 2. 调用Dify API获取分段
            String url = String.format("/datasets/%s/documents/%s/segments", datasetId, documentId);
            String response = difyApiClient.get(url, null);
            
            if (StringUtils.hasText(response)) {
                JSONObject result = JSON.parseObject(response);
                logger.info("获取文档分段成功: datasetId={}, documentId={}", datasetId, documentId);
                return ResultDomain.success("查询成功", result);
            }
            
            return ResultDomain.failure("获取文档分段失败");
        } catch (Exception e) {
            logger.error("获取文档分段异常: datasetId={}, documentId={}, error={}", datasetId, documentId, e.getMessage(), e);
            return ResultDomain.failure("获取文档分段异常: " + e.getMessage());
        }
    }

    @Override
    public ResultDomain<String> updateSegment(String datasetId, String documentId, String segmentId, Map<String, Object> requestBody) {
        // 1. 参数校验
        if (!StringUtils.hasText(datasetId)) {
            return ResultDomain.failure("数据集ID不能为空");
        }
        if (!StringUtils.hasText(documentId)) {
            return ResultDomain.failure("文档ID不能为空");
        }
        if (!StringUtils.hasText(segmentId)) {
            return ResultDomain.failure("分段ID不能为空");
        }

        try {
            // 2. 调用Dify API更新分段
            String url = String.format("/datasets/%s/documents/%s/segments/%s", datasetId, documentId, segmentId);
            String response = difyApiClient.patch(url, requestBody, null);
            
            logger.info("更新分段成功: datasetId={}, documentId={}, segmentId={}", datasetId, documentId, segmentId);
            return ResultDomain.success("更新成功", response);
        } catch (Exception e) {
            logger.error("更新分段异常: datasetId={}, documentId={}, segmentId={}, error={}", 
                    datasetId, documentId, segmentId, e.getMessage(), e);
            return ResultDomain.failure("更新分段异常: " + e.getMessage());
        }
    }

    @Override
    public ResultDomain<String> createSegment(String datasetId, String documentId, Map<String, Object> requestBody) {
        // 1. 参数校验
        if (!StringUtils.hasText(datasetId)) {
            return ResultDomain.failure("数据集ID不能为空");
        }
        if (!StringUtils.hasText(documentId)) {
            return ResultDomain.failure("文档ID不能为空");
        }

        try {
            // 2. 调用Dify API创建分段
            String url = String.format("/datasets/%s/documents/%s/segments", datasetId, documentId);
            String response = difyApiClient.post(url, requestBody, null);
            
            logger.info("创建分段成功: datasetId={}, documentId={}", datasetId, documentId);
            return ResultDomain.success("创建成功", response);
        } catch (Exception e) {
            logger.error("创建分段异常: datasetId={}, documentId={}, error={}", datasetId, documentId, e.getMessage(), e);
            return ResultDomain.failure("创建分段异常: " + e.getMessage());
        }
    }

    @Override
    public ResultDomain<String> deleteSegment(String datasetId, String documentId, String segmentId) {
        // 1. 参数校验
        if (!StringUtils.hasText(datasetId)) {
            return ResultDomain.failure("数据集ID不能为空");
        }
        if (!StringUtils.hasText(documentId)) {
            return ResultDomain.failure("文档ID不能为空");
        }
        if (!StringUtils.hasText(segmentId)) {
            return ResultDomain.failure("分段ID不能为空");
        }

        try {
            // 2. 调用Dify API删除分段
            String url = String.format("/datasets/%s/documents/%s/segments/%s", datasetId, documentId, segmentId);
            String response = difyApiClient.delete(url, null);
            
            logger.info("删除分段成功: datasetId={}, documentId={}, segmentId={}", datasetId, documentId, segmentId);
            return ResultDomain.success("删除成功", response);
        } catch (Exception e) {
            logger.error("删除分段异常: datasetId={}, documentId={}, segmentId={}, error={}", 
                    datasetId, documentId, segmentId, e.getMessage(), e);
            return ResultDomain.failure("删除分段异常: " + e.getMessage());
        }
    }

    @Override
    public ResultDomain<String> updateDocumentStatus(String datasetId, String action, Map<String, Object> requestBody) {
        // 1. 参数校验
        if (!StringUtils.hasText(datasetId)) {
            return ResultDomain.failure("数据集ID不能为空");
        }
        if (!StringUtils.hasText(action)) {
            return ResultDomain.failure("操作类型不能为空");
        }

        // 校验action合法性
        if (!action.equals("enable") && !action.equals("disable") && 
            !action.equals("archive") && !action.equals("un_archive")) {
            return ResultDomain.failure("操作类型不合法，支持：enable/disable/archive/un_archive");
        }

        try {
            // 2. 调用Dify API更新文档状态
            String url = String.format("/datasets/%s/documents/%s/status", datasetId, action);
            String response = difyApiClient.patch(url, requestBody, null);
            
            logger.info("更新文档状态成功: datasetId={}, action={}", datasetId, action);
            return ResultDomain.success("更新成功", response);
        } catch (Exception e) {
            logger.error("更新文档状态异常: datasetId={}, action={}, error={}", datasetId, action, e.getMessage(), e);
            return ResultDomain.failure("更新文档状态异常: " + e.getMessage());
        }
    }
}
