package org.dromara.ai.controller.app;

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

import java.util.Map;

/**
 * DIFY平台控制器
 * 提供DIFY平台的应用管理接口
 *
 * @author pengles
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/ai/dify")
@RequiredArgsConstructor
public class DifyController {
    
    private final DifyClientService difyService;

    /**
     * 获取应用列表
     *
     * @return 应用列表
     */
    @GetMapping("/apps")
    @Operation(summary = "列表应用", description = "获取DIFY平台的所有应用列表")
    public R<Map<String, Object>> apps() {
        try {
            log.debug("获取DIFY应用列表");
            String resp = difyService.get("/api/apps");
            return R.ok(Map.of("raw", resp));
        } catch (Exception e) {
            log.error("获取DIFY应用列表失败", e);
            return R.fail("DIFY调用失败: " + e.getMessage());
        }
    }

    /**
     * 创建或更新应用
     *
     * @param body 应用信息
     * @return 创建结果
     */
    @PostMapping("/apps")
    @Operation(summary = "创建应用", description = "在DIFY平台创建或更新应用")
    public R<Map<String, Object>> create(@RequestBody Map<String, Object> body) {
        try {
            log.info("创建DIFY应用");
            String resp = difyService.post("/api/apps", toJson(body));
            log.info("DIFY应用创建成功");
            return R.ok(Map.of("raw", resp));
        } catch (Exception e) {
            log.error("创建DIFY应用失败", e);
            return R.fail("DIFY调用失败: " + e.getMessage());
        }
    }

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