package com.huimv.employment.controller.mp;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.huimv.employment.integration.kb.KbOpenAiProxyService;
import com.huimv.employment.integration.kb.SseStreamSupport;
import com.huimv.employment.security.LoginUser;
import com.huimv.employment.security.LoginUserHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 智能体网关代理（小程序 JWT 鉴权；上游 Authorization 使用 fe.kb.api-key）。
 */
@RestController
@RequestMapping("/api/v1/mp/ai")
@Tag(name = "AI 对话", description = "智能体网关代理，需 JWT 鉴权")
@SecurityRequirement(name = "Authorization")
public class AiProxyController {

    private static final String HEADER_AGENT_ID = "X-Agent-Id";

    private final KbOpenAiProxyService kbOpenAiProxyService;
    private final ObjectMapper objectMapper;

    public AiProxyController(KbOpenAiProxyService kbOpenAiProxyService, ObjectMapper objectMapper) {
        this.kbOpenAiProxyService = kbOpenAiProxyService;
        this.objectMapper = objectMapper;
    }

    @GetMapping("/version")
    @Operation(summary = "获取版本信息", description = "透传上游 GET /api/version，用于健康检查。")
    public ResponseEntity<byte[]> getVersion() {
        return kbOpenAiProxyService.getVersion();
    }

    @PostMapping(value = "/console/chat", consumes = MediaType.APPLICATION_JSON_VALUE)
    @Operation(summary = "智能体对话（SSE 流式）",
            description = "透传上游 POST /api/console/chat，固定返回 text/event-stream。"
                    + "请求体示例：{\"input\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"你好\"}]}],"
                    + "\"session_id\":\"demo-001\",\"user_id\":\"1001\",\"channel\":\"console\"}。"
                    + "未传 user_id 时自动填充当前登录用户 ID；未传 channel 时默认为 console。"
                    + "可选请求头 X-Agent-Id，默认 default。")
    public void consoleChat(HttpServletRequest request,
                            HttpServletResponse response,
                            @RequestHeader(value = HEADER_AGENT_ID, required = false) String agentId) throws IOException {
        byte[] body = enrichConsoleChatBody(StreamUtils.copyToByteArray(request.getInputStream()));
        SseStreamSupport.prepareSseResponse(response);
        kbOpenAiProxyService.streamConsoleChat(body, agentId, response.getOutputStream());
        response.flushBuffer();
    }

    private byte[] enrichConsoleChatBody(byte[] body) throws IOException {
        if (body == null || body.length == 0) {
            return body;
        }
        JsonNode root = objectMapper.readTree(body);
        if (!(root instanceof ObjectNode)) {
            return body;
        }
        ObjectNode objectNode = (ObjectNode) root;
        if (!StringUtils.hasText(objectNode.path("user_id").asText(null))) {
            LoginUser loginUser = LoginUserHolder.require();
            objectNode.put("user_id", String.valueOf(loginUser.getUserId()));
        }
        if (!StringUtils.hasText(objectNode.path("channel").asText(null))) {
            objectNode.put("channel", "console");
        }
        return objectMapper.writeValueAsBytes(objectNode);
    }
}
