package provider

import "github.com/rose_cat707/luminary/internal/model"

type ProviderTypeMeta struct {
	Key   model.ProviderType `json:"key"`
	Label string             `json:"label"`
}

var allProviderTypes = []ProviderTypeMeta{
	{Key: model.ProviderOpenAI, Label: "OpenAI"},
	{Key: model.ProviderAnthropic, Label: "Anthropic"},
	{Key: model.ProviderAzureOpenAI, Label: "Azure OpenAI"},
	{Key: model.ProviderOpenRouter, Label: "OpenRouter"},
	{Key: model.ProviderOllama, Label: "Ollama"},
	{Key: model.ProviderCustom, Label: "Custom (OpenAI compatible)"},
	{Key: model.ProviderComfyUI, Label: "ComfyUI"},
}

func ProviderTypeLabel(t model.ProviderType) string {
	for _, m := range allProviderTypes {
		if m.Key == t {
			return m.Label
		}
	}
	return string(t)
}

// TypesForCategory 各出口分类支持的协议类型
func TypesForCategory(cat model.ProviderCategory) []ProviderTypeMeta {
	switch cat {
	case model.CategoryImage:
		return []ProviderTypeMeta{{Key: model.ProviderComfyUI, Label: "ComfyUI"}}
	case model.CategoryEmbedding:
		return filterTypes(
			model.ProviderOpenAI,
			model.ProviderAzureOpenAI,
			model.ProviderOpenRouter,
			model.ProviderOllama,
			model.ProviderCustom,
		)
	case model.CategoryRerank:
		return filterTypes(
			model.ProviderOpenAI,
			model.ProviderAzureOpenAI,
			model.ProviderOpenRouter,
			model.ProviderOllama,
			model.ProviderCustom,
		)
	default:
		return filterTypes(
			model.ProviderOpenAI,
			model.ProviderAnthropic,
			model.ProviderAzureOpenAI,
			model.ProviderOpenRouter,
			model.ProviderOllama,
			model.ProviderCustom,
		)
	}
}

func filterTypes(keys ...model.ProviderType) []ProviderTypeMeta {
	set := map[model.ProviderType]bool{}
	for _, k := range keys {
		set[k] = true
	}
	out := make([]ProviderTypeMeta, 0, len(keys))
	for _, m := range allProviderTypes {
		if set[m.Key] {
			out = append(out, m)
		}
	}
	return out
}

func DefaultProviderType(cat model.ProviderCategory) model.ProviderType {
	types := TypesForCategory(cat)
	if len(types) == 0 {
		return model.ProviderOpenAI
	}
	return types[0].Key
}

func IsTypeValidForCategory(cat model.ProviderCategory, t model.ProviderType) bool {
	for _, m := range TypesForCategory(cat) {
		if m.Key == t {
			return true
		}
	}
	return false
}

// AllProviderTypes 返回全部协议类型（用于管理台展示标签）
func AllProviderTypes() []ProviderTypeMeta {
	return append([]ProviderTypeMeta(nil), allProviderTypes...)
}
