package com.ruoyi.web.kb.controller;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.web.kb.service.KbOpenAiProxyService;
import com.ruoyi.web.kb.support.SseStreamSupport;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 大模型 OpenAI 兼容接口转发（管理端 / 移动端 AI 对话）。
 * <p>路径与 {@code doc/大模型对外API接口规范_0509.pdf} 一致；<b>须若依登录 Token</b>（走 Spring Security，非 {@code @Anonymous}）。
 * 上游鉴权由服务端 {@code ruoyi.kb.api-key} 注入，不使用客户端 {@code Authorization} 访问上游。</p>
 */
@RestController
@RequestMapping("/v1")
public class KbOpenAiProxyController
{
    private final KbOpenAiProxyService kbOpenAiProxyService;

    public KbOpenAiProxyController(KbOpenAiProxyService kbOpenAiProxyService)
    {
        this.kbOpenAiProxyService = kbOpenAiProxyService;
    }

    @GetMapping("/models")
    public ResponseEntity<byte[]> models()
    {
        return kbOpenAiProxyService.listModels();
    }

    @PostMapping(value = "/chat/completions", consumes = MediaType.APPLICATION_JSON_VALUE)
    public void chatCompletions(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        byte[] body = StreamUtils.copyToByteArray(request.getInputStream());
        if (kbOpenAiProxyService.isStreamRequest(body))
        {
            SseStreamSupport.prepareSseResponse(response);
            kbOpenAiProxyService.streamChatCompletions(body, response.getOutputStream());
            response.flushBuffer();
            return;
        }
        ResponseEntity<byte[]> upstream = kbOpenAiProxyService.chatCompletions(body);
        response.setStatus(upstream.getStatusCodeValue());
        MediaType contentType = upstream.getHeaders().getContentType();
        if (contentType != null)
        {
            response.setContentType(contentType.toString());
        }
        else
        {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        }
        byte[] respBody = upstream.getBody();
        if (respBody != null && respBody.length > 0)
        {
            response.getOutputStream().write(respBody);
        }
    }
}
