package app

import (
	"git.echol.cn/loser/ai_proxy/server/global"
	"git.echol.cn/loser/ai_proxy/server/model/app/request"
	"git.echol.cn/loser/ai_proxy/server/model/common/response"
	"git.echol.cn/loser/ai_proxy/server/service"
	"git.echol.cn/loser/ai_proxy/server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type AiProxyApi struct{}

var aiProxyService = service.ServiceGroupApp.AppServiceGroup.AiProxyService

// ChatCompletions OpenAI兼容的聊天补全接口
// @Tags AiProxy
// @Summary 聊天补全（OpenAI兼容）
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.ChatCompletionRequest true "聊天请求"
// @Success 200 {object} response.ChatCompletionResponse "聊天响应"
// @Router /v1/chat/completions [post]
func (a *AiProxyApi) ChatCompletions(c *gin.Context) {
	var req request.ChatCompletionRequest
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	userId := utils.GetUserID(c)

	// 处理流式响应
	if req.Stream {
		aiProxyService.ProcessChatCompletionStream(c, userId, &req)
		return
	}

	// 处理普通响应
	resp, err := aiProxyService.ProcessChatCompletion(c.Request.Context(), userId, &req)
	if err != nil {
		global.GVA_LOG.Error("处理聊天请求失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	c.JSON(200, resp)
}
