package llm

import (
	"net/http"

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

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

// Messages proxies Anthropic-compatible messages requests through the AgentTeam APR-backed proxy.
func (handler *LLMHandler) Messages(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, "messages")
	if !ok {
		handler.recordObservation(ctx, observation, llmUsageTotals{}, "rate_limit")
		return
	}
	if observation != nil {
		observation.queueWait = queueWait
	}
	defer release()

	anthropicProvider, ok := resolved.Provider.(types.AnthropicCompatible)
	if ok {
		resp, err := anthropicProvider.Messages(ctx.Request.Context(), ctx.Request.Header, resolved.Body)
		if err == nil {
			defer resp.Body.Close()
			handler.copyResponseWithObservation(ctx, resp, observation)
			return
		}
		if err != agentteambridge.ErrWireAPIUnsupported {
			handler.respondUpstreamError(ctx, observation, resolved.Provider.Name(), resolved.Model, "messages", err)
			return
		}
	}

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