package ai

import "strings"

func ApplyModelCatalog(upstream []map[string]any, catalog []ModelCatalogEntry) []map[string]any {
	if len(catalog) == 0 {
		return upstream
	}

	allowed := make(map[string]ModelCatalogEntry)
	for _, entry := range catalog {
		id := strings.TrimSpace(entry.ModelID)
		if id == "" || !entry.Enabled {
			continue
		}
		allowed[id] = entry
	}
	if len(allowed) == 0 {
		return []map[string]any{}
	}

	out := make([]map[string]any, 0, len(allowed))
	seen := make(map[string]struct{}, len(allowed))
	for _, model := range upstream {
		id, _ := model["id"].(string)
		id = strings.TrimSpace(id)
		entry, ok := allowed[id]
		if !ok {
			continue
		}
		seen[id] = struct{}{}
		out = append(out, catalogModel(id, entry.Label, model["owned_by"]))
	}
	for id, entry := range allowed {
		if _, ok := seen[id]; ok {
			continue
		}
		out = append(out, catalogModel(id, entry.Label, nil))
	}
	return out
}

func IsModelAllowed(model string, catalog []ModelCatalogEntry) bool {
	model = strings.TrimSpace(model)
	if model == "" || len(catalog) == 0 {
		return true
	}
	for _, entry := range catalog {
		if strings.TrimSpace(entry.ModelID) == model {
			return entry.Enabled
		}
	}
	return false
}

func catalogModel(id, label string, ownedBy any) map[string]any {
	display := strings.TrimSpace(label)
	if display == "" {
		display = id
	}
	out := map[string]any{
		"id":     id,
		"object": "model",
		"label":  display,
	}
	if ownedBy != nil {
		out["owned_by"] = ownedBy
	}
	return out
}
