package websearch

import (
	"fmt"
	"strings"
)

type ProviderType string

const ProviderBrave ProviderType = "brave"

type Provider struct {
	ID     string       `json:"id"`
	Name   string       `json:"name"`
	Type   ProviderType `json:"type"`
	APIKey string       `json:"api_key,omitempty"`
}

type Settings struct {
	DefaultProviderID string     `json:"default_provider_id"`
	Providers         []Provider `json:"providers"`
}

func ResolveProvider(settings Settings) (Provider, error) {
	providerID := strings.TrimSpace(settings.DefaultProviderID)
	if providerID != "" {
		for _, p := range settings.Providers {
			if p.ID == providerID && providerConfigured(p) {
				return p, nil
			}
		}
	}
	for _, p := range settings.Providers {
		if providerConfigured(p) {
			return p, nil
		}
	}
	return Provider{}, fmt.Errorf("no search provider configured")
}

func providerConfigured(p Provider) bool {
	return strings.TrimSpace(p.APIKey) != "" && strings.TrimSpace(string(p.Type)) != ""
}
