package llm

import (
	"net/http"
	"sort"

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

// Models returns all models currently exposed by the AgentTeam APR-backed proxy.
func (handler *LLMHandler) Models(ctx *gin.Context) {
	type modelResponse struct {
		ID      string `json:"id"`
		Object  string `json:"object"`
		OwnedBy string `json:"owned_by"`
	}

	authorized, ok := llmProxyAuthorizationFromContext(ctx.Request.Context())
	if !ok {
		ctx.JSON(http.StatusUnauthorized, gin.H{"error": "missing llm proxy authorization"})
		return
	}
	data := make([]modelResponse, 0)
	if authorized.WorkspaceID != "" {
		for _, model := range authorized.AllowedModels {
			data = append(data, modelResponse{
				ID:      model,
				Object:  "model",
				OwnedBy: "agentteam",
			})
		}
	} else {
		if handler.aprDispatcher == nil {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": "provider is unavailable"})
			return
		}
		models := handler.aprDispatcher.ProviderModels()[authorized.OrganizationProviderID]
		if len(models) == 0 {
			ctx.JSON(http.StatusBadRequest, gin.H{"error": "provider is unavailable"})
			return
		}
		for _, model := range models {
			data = append(data, modelResponse{
				ID:      model.ID,
				Object:  "model",
				OwnedBy: authorized.OrganizationProviderID,
			})
		}
	}
	sort.Slice(data, func(i, j int) bool {
		if data[i].OwnedBy != data[j].OwnedBy {
			return data[i].OwnedBy < data[j].OwnedBy
		}
		return data[i].ID < data[j].ID
	})

	ctx.JSON(http.StatusOK, gin.H{
		"object": "list",
		"data":   data,
	})
}
