package ai

import (
	"strconv"
	"strings"
	"time"

	"ops-assistant/models"

	"gorm.io/gorm"
)

func LoadClient(db *gorm.DB) *Client {
	if db == nil {
		return nil
	}
	get := func(key string) string {
		var sset models.AppSetting
		if err := db.Where("key = ?", key).First(&sset).Error; err == nil {
			return strings.TrimSpace(sset.Value)
		}
		return ""
	}
	if strings.ToLower(get("ai_enabled")) != "true" {
		return nil
	}
	baseURL := get("ai_base_url")
	apiKey := get("ai_api_key")
	model := get("ai_model")
	to := 15
	if v := get("ai_timeout_seconds"); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n > 0 {
			to = n
		}
	}
	if baseURL == "" || apiKey == "" || model == "" {
		return nil
	}
	return &Client{BaseURL: baseURL, APIKey: apiKey, Model: model, Timeout: time.Duration(to) * time.Second}
}
