package llm

import (
	"net/http"

	"github.com/tidbcloud/AgentTeam/internal/apr/types"

	"github.com/gin-gonic/gin"
)

// ChatCompletions proxies OpenAI chat completion requests through the AgentTeam APR-backed proxy.
func (handler *LLMHandler) ChatCompletions(ctx *gin.Context) {
	resolved, ok := handler.resolveRequest(ctx)
	if !ok {
		return
	}
	observation, _ := handler.newUsageObservation(ctx, resolved)
	if !handler.enforceQuota(ctx, observation) {
		return
	}
	queueWait, release, ok := handler.acquireConcurrency(ctx, resolved, "chat_completions")
	if !ok {
		handler.recordObservation(ctx, observation, llmUsageTotals{}, "rate_limit")
		return
	}
	if observation != nil {
		observation.queueWait = queueWait
	}
	defer release()

	openAIProvider, ok := resolved.Provider.(types.OpenAICompatible)
	if !ok {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "provider does not support OpenAI-compatible chat completions"})
		handler.recordObservation(ctx, observation, llmUsageTotals{}, "bad_request")
		return
	}

	resp, err := openAIProvider.ChatCompletion(ctx.Request.Context(), ctx.Request.Header, resolved.Body)
	if err != nil {
		handler.respondUpstreamError(ctx, observation, resolved.Provider.Name(), resolved.Model, "chat completion", err)
		return
	}
	defer resp.Body.Close()

	handler.copyOpenAIChatCompletionResponseWithObservation(ctx, resp, observation)
}
