internal/config/config.go (view raw)
1package config
2
3import (
4 "fmt"
5 "os"
6 "path/filepath"
7
8 "github.com/spf13/viper"
9
10 "llm_aggregator/internal/cli"
11 "llm_aggregator/internal/defaults"
12 "llm_aggregator/internal/progress"
13 "llm_aggregator/internal/runtime"
14 "llm_aggregator/internal/style"
15)
16
17// Config holds the application configuration loaded from TOML file, environment variables, and CLI arguments.
18type Config struct {
19 // Feed aggregation options
20 MaxArticlesPerFeed int `mapstructure:"max_articles_per_feed"`
21 MaxDaysOld int `mapstructure:"max_days_old"`
22 MaxTotalArticles int `mapstructure:"max_total_articles"`
23 IncludeKeywords string `mapstructure:"include_keywords"`
24 ExcludeKeywords string `mapstructure:"exclude_keywords"`
25
26 // LLM API options
27 APIKey string `mapstructure:"api_key"`
28 BaseURL string `mapstructure:"base_url"`
29 Model string `mapstructure:"model"`
30 MaxTokens int `mapstructure:"max_tokens"`
31 Temperature float64 `mapstructure:"temperature"`
32
33 // System prompt
34 SystemPrompt string `mapstructure:"system_prompt"`
35
36 // Output options
37 Output string `mapstructure:"output"`
38 OutputFile string `mapstructure:"output_file"`
39 IncludeArticles bool `mapstructure:"include_articles"`
40}
41
42// GetViper returns the global viper instance with all configuration sources set up.
43// The precedence order is: CLI flags > Environment variables > Config file > Defaults.
44//
45// NOTE: Viper uses a singleton pattern. Subsequent calls to GetViper() return the SAME
46// instance with all previously set values. This means defaults are only set once,
47// environment vars are bound once, and the config file is read once. Do NOT call this
48// expecting a fresh state — if you need a fresh instance for testing, use viper.New() directly.
49func GetViper() *viper.Viper {
50 // Set defaults first (lowest priority)
51 setDefaults()
52 // Initialise or get existing Viper instance
53 v := viper.GetViper()
54 // Ensure defaults are set (for fresh instances)
55 setDefaultsOn(v)
56 // Set environment variable prefix
57 v.SetEnvPrefix("LLM_AGGREGATOR")
58 v.AutomaticEnv()
59 // Bind environment variables to config fields
60 bindEnvVars(v)
61 // Get config path from XDG
62 configPath, err := GetConfigPath()
63 if err == nil {
64 // Set config file path
65 v.SetConfigFile(configPath)
66 // Debug: show what config file is being used
67 // Try to read config file
68 if err := v.ReadInConfig(); err != nil {
69 // If config file doesn't exist, that's OK - we'll use defaults + env vars
70 if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
71 fmt.Fprintln(os.Stderr, style.Warningf("error reading config file: %v", err))
72 } else {
73 }
74 } else {
75 }
76 }
77 return v
78}
79
80// setDefaults sets default values on the global viper instance.
81func setDefaults() {
82 v := viper.GetViper()
83 setDefaultsOn(v)
84}
85
86// setDefaultsOn sets default values on the given viper instance.
87func setDefaultsOn(v *viper.Viper) {
88 // Feed aggregation defaults
89 v.SetDefault("max_articles_per_feed", defaults.DefaultMaxArticlesPerFeed)
90 v.SetDefault("max_days_old", defaults.DefaultMaxDaysOld)
91 v.SetDefault("max_total_articles", defaults.DefaultMaxTotalArticles)
92 // LLM API defaults
93 v.SetDefault("base_url", defaults.DefaultBaseURL)
94 v.SetDefault("model", defaults.DefaultModel)
95 v.SetDefault("max_tokens", defaults.DefaultMaxTokens)
96 v.SetDefault("temperature", defaults.DefaultTemperature)
97 // System prompt default
98 v.SetDefault("system_prompt", defaults.DefaultSystemPrompt)
99 // Output defaults
100 v.SetDefault("output", defaults.DefaultOutput)
101 v.SetDefault("include_articles", defaults.DefaultIncludeArticles)
102}
103
104// BindCLIArgs binds CLI argument values to viper with highest precedence.
105// This should be called after parsing CLI arguments to override config file/env defaults.
106func BindCLIArgs(v *viper.Viper, args map[string]any) {
107 for key, value := range args {
108 if value != nil && !isZero(value) {
109 v.Set(key, value)
110 }
111 }
112}
113
114// isZero checks if a value is the zero value for its type.
115//
116// NOTE: This function is critical for CLI argument handling. Pointer types
117// (*string, *int, etc.) return true only when nil (not provided), NOT when
118// pointing to a zero value. This allows distinguishing between "flag not
119// provided" (nil) vs "flag explicitly set to zero" (e.g., --temperature 0
120// should override default, but no flag means preserve default).
121func isZero(v any) bool {
122 // Handle nil interface values first (before type switch)
123 if v == nil {
124 return true
125 }
126 switch val := v.(type) {
127 case string:
128 return val == ""
129 case int:
130 return val == 0
131 case int8:
132 return val == 0
133 case int16:
134 return val == 0
135 case int32:
136 return val == 0
137 case int64:
138 return val == 0
139 case float32:
140 return val == 0.0
141 case float64:
142 return val == 0.0
143 case bool:
144 return !val
145 case *string:
146 return val == nil
147 case *int:
148 return val == nil
149 case *int8:
150 return val == nil
151 case *int16:
152 return val == nil
153 case *int32:
154 return val == nil
155 case *int64:
156 return val == nil
157 case *float32:
158 return val == nil
159 case *float64:
160 return val == nil
161 case *bool:
162 return val == nil
163 default:
164 return false
165 }
166}
167
168// ViperToRuntime converts viper configuration directly to runtime.Runtime.
169func ViperToRuntime(v *viper.Viper, feedsFile, prompt string) *runtime.Runtime {
170 rt := &runtime.Runtime{
171 FeedsFile: feedsFile,
172 Prompt: prompt,
173 Progress: &progress.NoopLogger{},
174 }
175 // Feed aggregation options
176 rt.MaxArticlesPerFeed = v.GetInt("max_articles_per_feed")
177 rt.MaxDaysOld = v.GetInt("max_days_old")
178 rt.MaxTotalArticles = v.GetInt("max_total_articles")
179 // Keywords
180 includeKeywords := v.GetString("include_keywords")
181 excludeKeywords := v.GetString("exclude_keywords")
182 if includeKeywords != "" {
183 rt.IncludeKeywords = cli.ParseKeywords(includeKeywords)
184 }
185 if excludeKeywords != "" {
186 rt.ExcludeKeywords = cli.ParseKeywords(excludeKeywords)
187 }
188 // LLM API options
189 rt.APIKey = v.GetString("api_key")
190 rt.BaseURL = v.GetString("base_url")
191 rt.Model = v.GetString("model")
192 rt.MaxTokens = v.GetInt("max_tokens")
193 rt.Temperature = v.GetFloat64("temperature")
194 // System prompt
195 rt.SystemPrompt = v.GetString("system_prompt")
196 // Output options
197 rt.Output = v.GetString("output")
198 rt.OutputFile = v.GetString("output_file")
199 rt.IncludeArticles = v.GetBool("include_articles")
200 return rt
201}
202
203// bindEnvVars binds environment variables to viper keys.
204func bindEnvVars(v *viper.Viper) {
205 // Feed aggregation options
206 v.BindEnv("max_articles_per_feed", "LLM_AGGREGATOR_MAX_ARTICLES_PER_FEED")
207 v.BindEnv("max_days_old", "LLM_AGGREGATOR_MAX_DAYS_OLD")
208 v.BindEnv("max_total_articles", "LLM_AGGREGATOR_MAX_TOTAL_ARTICLES")
209 v.BindEnv("include_keywords", "LLM_AGGREGATOR_INCLUDE_KEYWORDS")
210 v.BindEnv("exclude_keywords", "LLM_AGGREGATOR_EXCLUDE_KEYWORDS")
211 // LLM API options
212 v.BindEnv("api_key", "LLM_AGGREGATOR_API_KEY")
213 v.BindEnv("base_url", "LLM_AGGREGATOR_BASE_URL")
214 v.BindEnv("model", "LLM_AGGREGATOR_MODEL")
215 v.BindEnv("max_tokens", "LLM_AGGREGATOR_MAX_TOKENS")
216 v.BindEnv("temperature", "LLM_AGGREGATOR_TEMPERATURE")
217 // System prompt
218 v.BindEnv("system_prompt", "LLM_AGGREGATOR_SYSTEM_PROMPT")
219 // Output options
220 v.BindEnv("output", "LLM_AGGREGATOR_OUTPUT")
221 v.BindEnv("output_file", "LLM_AGGREGATOR_OUTPUT_FILE")
222 v.BindEnv("include_articles", "LLM_AGGREGATOR_INCLUDE_ARTICLES")
223}
224
225// GetConfigPath returns the path to the config file.
226func GetConfigPath() (string, error) {
227 configDir, err := os.UserConfigDir()
228 if err != nil {
229 return "", fmt.Errorf("failed to get user config directory: %w", err)
230 }
231 return filepath.Join(configDir, "llm_aggregator", "config.toml"), nil
232}