package config

import (
	ai "ai-css/library/modelprovider/consts"
	"context"
	"fmt"
	"sync"
)

type Manager struct {
	mu              sync.RWMutex
	providerConfigs map[ai.ProviderName]ProviderConfig
	configRepo      Repo
}

func NewManager(confRepo Repo) *Manager {
	return &Manager{providerConfigs: make(map[ai.ProviderName]ProviderConfig), configRepo: confRepo}
}

type Repo interface {
	GetAllConfig() (map[ai.ProviderName]ProviderConfig, error) // providerName: apikeys
}

func (m *Manager) LoadConfigs(ctx context.Context) error {
	if m.configRepo == nil {
		return fmt.Errorf("load from database failed: repo is nil")
	}
	allconfigs, err := m.configRepo.GetAllConfig()
	if err != nil {
		return fmt.Errorf("get all config from database failed err:%w", err)
	}
	m.mu.Lock()
	defer m.mu.Unlock()

	m.providerConfigs = make(map[ai.ProviderName]ProviderConfig) // 清空
	for name, conf := range allconfigs {
		m.providerConfigs[name] = conf
	}
	return nil
}

func (m *Manager) SetConfigByProviderName(name ai.ProviderName, config ProviderConfig) {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.providerConfigs[name] = config
}

func (m *Manager) GetConfigByProviderName(name ai.ProviderName) (ProviderConfig, bool) {
	m.mu.RLock()
	defer m.mu.RUnlock()

	conf, ok := m.providerConfigs[name]
	return conf, ok
}
