package org.dromara.ai.controller.app;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.ai.platform.FastGptService;
import org.dromara.common.core.domain.R;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * FastGPT平台控制器
 * 提供FastGPT平台的知识库检索、工作流编排和上下文管理接口
 *
 * @author pengles
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/ai/fastgpt")
@RequiredArgsConstructor
public class FastGptController {
    
    private final FastGptService fastGptService;

    /**
     * 知识库检索
     *
     * @param body 检索参数
     * @return 检索结果
     */
    @PostMapping("/knowledge/search")
    @Operation(summary = "知识库检索", description = "在FastGPT平台的知识库中进行检索")
    public R<Map<String, Object>> search(@RequestBody Map<String, Object> body) {
        try {
            log.debug("FastGPT知识库检索请求");
            String resp = fastGptService.post("/api/knowledge/search", toJson(body));
            return R.ok(Map.of("raw", resp));
        } catch (Exception e) {
            log.error("FastGPT知识库检索失败", e);
            return R.fail("FastGPT调用失败: " + e.getMessage());
        }
    }

    /**
     * 工作流编排
     *
     * @param body 工作流参数
     * @return 执行结果
     */
    @PostMapping("/workflow/run")
    @Operation(summary = "工作流编排", description = "运行FastGPT平台的工作流")
    public R<Map<String, Object>> workflow(@RequestBody Map<String, Object> body) {
        try {
            log.info("FastGPT工作流执行请求");
            String resp = fastGptService.post("/api/workflow/run", toJson(body));
            log.info("FastGPT工作流执行成功");
            return R.ok(Map.of("raw", resp));
        } catch (Exception e) {
            log.error("FastGPT工作流执行失败", e);
            return R.fail("FastGPT调用失败: " + e.getMessage());
        }
    }

    /**
     * 获取上下文
     *
     * @param sessionId 会话ID
     * @return 上下文信息
     */
    @GetMapping("/context/{sessionId}")
    @Operation(summary = "上下文管理", description = "获取指定会话的上下文信息")
    public R<Map<String, Object>> context(
            @Parameter(description = "会话ID", required = true)
            @PathVariable String sessionId) {
        try {
            log.debug("获取FastGPT上下文 - 会话ID: {}", sessionId);
            String resp = fastGptService.get("/api/context/" + sessionId);
            return R.ok(Map.of("raw", resp));
        } catch (Exception e) {
            log.error("获取FastGPT上下文失败 - 会话ID: {}", sessionId, e);
            return R.fail("FastGPT调用失败: " + e.getMessage());
        }
    }

    /**
     * 将Map转换为JSON字符串
     */
    private String toJson(Map<String, Object> m) {
        return org.dromara.common.json.utils.JsonUtils.toJsonString(m);
    }
}
