internal/config.go

823 lines · 25458 bytes · executable

  1package internal
  2
  3import (
  4	"bufio"
  5	"context"
  6	"encoding/json"
  7	"fmt"
  8	"sort"
  9
 10	// "io"
 11	"net/http"
 12	"net/url"
 13	"os"
 14	"path/filepath"
 15	"reflect"
 16	"strconv"
 17	"strings"
 18	"time"
 19
 20	"github.com/pkg/browser"
 21)
 22
 23const (
 24	anilistOAuthURL     = "https://anilist.co/api/v2/oauth"
 25	anilistClientID     = "20686"
 26	anilistClientSecret = "APfx41cOgSQVMvi88v7PbN7g6kzed2ZQRcxmACod"
 27	anilistRedirectURI  = "http://localhost:8000/oauth/callback"
 28	anilistServerPort   = 8000
 29)
 30
 31// AnilistToken represents the OAuth token response from Anilist
 32type AnilistToken struct {
 33	AccessToken  string    `json:"access_token"`
 34	TokenType    string    `json:"token_type"`
 35	ExpiresIn    int       `json:"expires_in"`
 36	RefreshToken string    `json:"refresh_token"`
 37	ExpiresAt    time.Time `json:"expires_at"`
 38}
 39
 40// CurdConfig struct with field names that match the config keys
 41type CurdConfig struct {
 42	Player                     string   `config:"Player"`
 43	MpvArgs                    []string `config:"MpvArgs"`
 44	MpvPlaybackStartTimeout    int      `config:"MpvPlaybackStartTimeout"`
 45	SubsLanguage               string   `config:"SubsLanguage"`
 46	SubOrDub                   string   `config:"SubOrDub"`
 47	SubStyle                   string   `config:"SubStyle"`
 48	StoragePath                string   `config:"StoragePath"`
 49	AnimeNameLanguage          string   `config:"AnimeNameLanguage"`
 50	MenuOrder                  string   `config:"MenuOrder"`
 51	PercentageToMarkComplete   int      `config:"PercentageToMarkComplete"`
 52	NextEpisodePrompt          bool     `config:"NextEpisodePrompt"`
 53	SkipOp                     bool     `config:"SkipOp"`
 54	SkipEd                     bool     `config:"SkipEd"`
 55	SkipFiller                 bool     `config:"SkipFiller"`
 56	ImagePreview               bool     `config:"ImagePreview"`
 57	SkipRecap                  bool     `config:"SkipRecap"`
 58	RofiSelection              bool     `config:"RofiSelection"`
 59	CurrentCategory            bool     `config:"CurrentCategory"`
 60	ScoreOnCompletion          bool     `config:"ScoreOnCompletion"`
 61	SaveMpvSpeed               bool     `config:"SaveMpvSpeed"`
 62	AddMissingOptions          bool     `config:"AddMissingOptions"`
 63	AlternateScreen            bool     `config:"AlternateScreen"`
 64	DiscordPresence            bool     `config:"DiscordPresence"`
 65	DiscordClientId            string   `config:"DiscordClientId"`
 66	VimKeys                    bool     `config:"VimKeys"`
 67	CheckUpdates               bool     `config:"CheckUpdates"`
 68	MpvEpisodePlaylist         bool     `config:"MpvEpisodePlaylist"`
 69	Provider                   string   `config:"Provider"`
 70	DisabledProviders          string   `config:"DisabledProviders"`
 71	ManualProviderSearch       bool     `config:"ManualProviderSearch"`
 72	TrackingLocal              bool     `config:"TrackingLocal"`
 73	TrackingRemote             string   `config:"TrackingRemote"`
 74	TrackingConfigured         bool     `config:"TrackingConfigured"`
 75	MyAnimeListClientID        string   `config:"MyAnimeListClientID"`
 76	MyAnimeListClientSecret    string   `config:"MyAnimeListClientSecret"`
 77	MyAnimeListImported        bool     `config:"MyAnimeListImported"`
 78	MyAnimeListImportDismissed bool     `config:"MyAnimeListImportDismissed"`
 79	ShowNewEpisodes            bool     `config:"ShowNewEpisodes"`
 80}
 81
 82const (
 83	DefaultMpvPlaybackStartTimeout = 20
 84	maxMpvPlaybackStartTimeout     = 600
 85)
 86
 87func MpvPlaybackStartTimeoutDuration(config *CurdConfig) time.Duration {
 88	seconds := DefaultMpvPlaybackStartTimeout
 89	if config != nil && config.MpvPlaybackStartTimeout > 0 {
 90		seconds = config.MpvPlaybackStartTimeout
 91	}
 92	return time.Duration(seconds) * time.Second
 93}
 94
 95func GetStoragePath() string {
 96	if globalConfig != nil && globalConfig.StoragePath != "" {
 97		return os.ExpandEnv(globalConfig.StoragePath)
 98	}
 99	return filepath.Join(os.ExpandEnv("$HOME"), ".local", "share", "curd")
100}
101
102// Default configuration values as a map
103func defaultConfigMap() map[string]string {
104	return map[string]string{
105		"Player":                     "mpv",
106		"MpvArgs":                    "[]",
107		"MpvPlaybackStartTimeout":    "20",
108		"StoragePath":                "$HOME/.local/share/curd",
109		"AnimeNameLanguage":          "english",
110		"SubsLanguage":               "english",
111		"MenuOrder":                  "CURRENT,ALL,UNTRACKED,UPDATE,REMAP_PROVIDER,CONTINUE_LAST,TRACKER,PROVIDER",
112		"SubOrDub":                   "sub",
113		"SubStyle":                   "ask",
114		"PercentageToMarkComplete":   "85",
115		"NextEpisodePrompt":          "false",
116		"SkipOp":                     "true",
117		"SkipEd":                     "true",
118		"SkipFiller":                 "true",
119		"SkipRecap":                  "true",
120		"RofiSelection":              "false",
121		"ImagePreview":               "false",
122		"ScoreOnCompletion":          "true",
123		"SaveMpvSpeed":               "true",
124		"AddMissingOptions":          "true",
125		"AlternateScreen":            "true",
126		"DiscordPresence":            "true",
127		"DiscordClientId":            "1287457464148820089",
128		"VimKeys":                    "false",
129		"CheckUpdates":               "true",
130		"MpvEpisodePlaylist":         "true",
131		"Provider":                   "stacked",
132		"DisabledProviders":          "[]",
133		"ManualProviderSearch":       "false",
134		"TrackingLocal":              "true",
135		"TrackingRemote":             "anilist",
136		"TrackingConfigured":         "false",
137		"MyAnimeListClientID":        "f76d4c827152327b60654285d221222c",
138		"MyAnimeListClientSecret":    "",
139		"MyAnimeListImported":        "false",
140		"MyAnimeListImportDismissed": "false",
141		"ShowNewEpisodes":            "true",
142	}
143}
144
145// VimKeysEnabled reports whether selection menus should use vim-style motions.
146func VimKeysEnabled(config *CurdConfig) bool {
147	if config != nil {
148		return config.VimKeys
149	}
150	if globalConfig != nil {
151		return globalConfig.VimKeys
152	}
153	return false
154}
155
156var globalConfig *CurdConfig
157
158func SetGlobalConfig(config *CurdConfig) {
159	globalConfig = config
160}
161
162func GetGlobalConfig() *CurdConfig {
163	return globalConfig
164}
165
166func useEnglishAnimeNames(config *CurdConfig) bool {
167	return config == nil || strings.EqualFold(strings.TrimSpace(config.AnimeNameLanguage), "english")
168}
169
170// Helper function to parse string array from config
171func parseStringArray(value string) []string {
172	value = strings.TrimSpace(value)
173	var parsed []string
174	if err := json.Unmarshal([]byte(value), &parsed); err == nil {
175		result := make([]string, 0, len(parsed))
176		for _, part := range parsed {
177			part = strings.TrimSpace(part)
178			if part != "" {
179				result = append(result, part)
180			}
181		}
182		return result
183	}
184
185	// Remove brackets and split by comma
186	value = strings.TrimPrefix(value, "[")
187	value = strings.TrimSuffix(value, "]")
188	if value == "" {
189		return nil
190	}
191
192	// Split by comma and trim spaces and quotes from each element
193	parts := strings.Split(value, ",")
194	result := make([]string, 0, len(parts))
195	for _, part := range parts {
196		// Trim spaces and quotes
197		part = strings.TrimSpace(part)
198		part = strings.Trim(part, "\"")
199		if part != "" {
200			result = append(result, part)
201		}
202	}
203	return result
204}
205
206var GlobalConfigPath string
207
208func persistSubStylePreference(style string) error {
209	style = strings.ToLower(strings.TrimSpace(style))
210	if style != "soft" && style != "hard" {
211		return nil
212	}
213	if cfg := GetGlobalConfig(); cfg != nil {
214		cfg.SubStyle = style
215	}
216	if strings.TrimSpace(GlobalConfigPath) == "" {
217		return nil
218	}
219	configMap, err := LoadConfigFromFile(GlobalConfigPath)
220	if err != nil {
221		return err
222	}
223	configMap["SubStyle"] = style
224	return SaveConfigToFile(GlobalConfigPath, configMap)
225}
226
227// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct
228func LoadConfig(configPath string) (CurdConfig, error) {
229	configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME
230	GlobalConfigPath = configPath
231	createdConfig := false
232
233	// Check if config file exists
234	if _, err := os.Stat(configPath); os.IsNotExist(err) {
235		// Create the config file with default values if it doesn't exist
236		CurdOut("Config file not found. Creating default config...")
237		if err := createDefaultConfig(configPath); err != nil {
238			return CurdConfig{}, fmt.Errorf("error creating default config file: %v", err)
239		}
240		createdConfig = true
241	}
242
243	// Load the config from file
244	configMap, err := LoadConfigFromFile(configPath)
245	if err != nil {
246		return CurdConfig{}, fmt.Errorf("error loading config file: %v", err)
247	}
248
249	// Check AddMissingOptions setting first
250	addMissing := true
251	if val, exists := configMap["AddMissingOptions"]; exists {
252		if parsed, parseErr := strconv.ParseBool(val); parseErr == nil {
253			addMissing = parsed
254		}
255	}
256
257	_, hadTrackingRemote := configMap["TrackingRemote"]
258	_, hadTrackingConfigured := configMap["TrackingConfigured"]
259	legacyConfig := !createdConfig && !hadTrackingRemote && !hadTrackingConfigured
260
261	// fileMap = keys actually present on disk.
262	// workMap = file keys + in-memory defaults for PopulateConfig.
263	fileMap := configMap
264	workMap := make(map[string]string, len(fileMap)+len(defaultConfigMap()))
265	for key, value := range fileMap {
266		workMap[key] = value
267	}
268	for key, defaultValue := range defaultConfigMap() {
269		if _, exists := workMap[key]; !exists {
270			workMap[key] = defaultValue
271		}
272	}
273
274	// One-time legacy tracking migration: only touch tracking keys on disk.
275	updated := false
276	if legacyConfig {
277		fileMap["TrackingLocal"] = "true"
278		fileMap["TrackingRemote"] = TrackingRemoteAniList
279		fileMap["TrackingConfigured"] = "true"
280		workMap["TrackingLocal"] = "true"
281		workMap["TrackingRemote"] = TrackingRemoteAniList
282		workMap["TrackingConfigured"] = "true"
283		updated = true
284	}
285
286	if providerValue, exists := fileMap["Provider"]; exists {
287		normalizedProviderValue := canonicalProviderConfigValue(providerValue)
288		if normalizedProviderValue != providerValue {
289			fileMap["Provider"] = normalizedProviderValue
290			workMap["Provider"] = normalizedProviderValue
291			updated = true
292		}
293	}
294
295	// New config keys are NOT bulk-appended here. Only MigrateOnVersionUpgrade
296	// injects options registered in configOptionsIntroducedInVersion() for the
297	// versions the user actually crossed — so sparse configs never get every
298	// historical default dumped in on a normal launch.
299
300	// Persist legacy tracking / provider-token normalize (rewrite only those cases).
301	if addMissing && updated {
302		if err := SaveConfigToFile(configPath, fileMap); err != nil {
303			return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err)
304		}
305	}
306
307	// Populate the CurdConfig struct from the complete (in-memory) work map
308	config := PopulateConfig(workMap)
309	normalizeTrackingConfig(&config)
310
311	return config, nil
312}
313
314// Create a config file with default values in key=value format
315// Ensure the directory exists before creating the file
316func createDefaultConfig(path string) error {
317	defaultConfig := defaultConfigMap()
318
319	// Ensure the directory exists
320	dir := filepath.Dir(path)
321	if err := os.MkdirAll(dir, 0o755); err != nil {
322		return fmt.Errorf("error creating directory: %v", err)
323	}
324
325	file, err := os.Create(path)
326	if err != nil {
327		return fmt.Errorf("error creating file: %v", err)
328	}
329	defer file.Close()
330
331	writer := bufio.NewWriter(file)
332	for key, value := range defaultConfig {
333		line := fmt.Sprintf("%s=%s\n", key, value)
334		if _, err := writer.WriteString(line); err != nil {
335			return fmt.Errorf("error writing to file: %v", err)
336		}
337	}
338	if err := writer.Flush(); err != nil {
339		return fmt.Errorf("error flushing writer: %v", err)
340	}
341	return nil
342}
343
344// authenticateWithBrowser performs OAuth authentication using browser
345func authenticateWithBrowser(tokenPath string) (string, error) {
346	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
347	defer cancel()
348
349	// Try to load existing token first
350	if token, err := loadToken(tokenPath); err == nil && isTokenValid(token) {
351		return token.AccessToken, nil
352	}
353
354	// Start local server to handle OAuth callback
355	callbackCh := make(chan string, 1)
356	errCh := make(chan error, 1)
357	mux := http.NewServeMux()
358	srv := &http.Server{
359		Addr:    fmt.Sprintf(":%d", anilistServerPort),
360		Handler: mux,
361	}
362
363	// Handle OAuth callback - for authorization code grant, code comes in query params
364	mux.HandleFunc("/oauth/callback", func(w http.ResponseWriter, r *http.Request) {
365		code := r.URL.Query().Get("code")
366		errorParam := r.URL.Query().Get("error")
367
368		w.Header().Set("Content-Type", "text/html")
369
370		if errorParam != "" {
371			w.WriteHeader(http.StatusBadRequest)
372			html := fmt.Sprintf(`<!DOCTYPE html>
373<html>
374<head>
375    <title>Curd Authentication</title>
376    <style>
377        body { font-family: Arial, sans-serif; margin: 50px; text-align: center; background: #1a1a1a; color: white; }
378        .error { color: #f44336; font-size: 18px; margin-bottom: 20px; }
379    </style>
380</head>
381<body>
382    <div class="error">Authentication failed: %s</div>
383    <p>You can close this window and try again.</p>
384</body>
385</html>`, errorParam)
386			fmt.Fprint(w, html)
387			errCh <- fmt.Errorf("oauth error: %s", errorParam)
388			return
389		}
390
391		if code == "" {
392			w.WriteHeader(http.StatusBadRequest)
393			html := `<!DOCTYPE html>
394<html>
395<head>
396    <title>Curd Authentication</title>
397    <style>
398        body { font-family: Arial, sans-serif; margin: 50px; text-align: center; background: #1a1a1a; color: white; }
399        .error { color: #f44336; font-size: 18px; margin-bottom: 20px; }
400    </style>
401</head>
402<body>
403    <div class="error">No authorization code received</div>
404    <p>You can close this window and try again.</p>
405</body>
406</html>`
407			fmt.Fprint(w, html)
408			errCh <- fmt.Errorf("no authorization code received")
409			return
410		}
411
412		// Exchange authorization code for access token
413		go func() {
414			tokenURL := fmt.Sprintf("%s/token", anilistOAuthURL)
415			data := url.Values{
416				"grant_type":    {"authorization_code"},
417				"client_id":     {anilistClientID},
418				"client_secret": {anilistClientSecret},
419				"redirect_uri":  {anilistRedirectURI},
420				"code":          {code},
421			}
422
423			resp, err := sharedHTTPClient.PostForm(tokenURL, data)
424			if err != nil {
425				errCh <- fmt.Errorf("failed to exchange code for token: %w", err)
426				return
427			}
428			defer resp.Body.Close()
429
430			if resp.StatusCode != http.StatusOK {
431				errCh <- fmt.Errorf("token exchange failed with status: %d", resp.StatusCode)
432				return
433			}
434
435			var tokenResponse struct {
436				AccessToken string `json:"access_token"`
437				TokenType   string `json:"token_type"`
438				ExpiresIn   int    `json:"expires_in"`
439			}
440
441			if err := json.NewDecoder(resp.Body).Decode(&tokenResponse); err != nil {
442				errCh <- fmt.Errorf("failed to parse token response: %w", err)
443				return
444			}
445
446			if tokenResponse.AccessToken == "" {
447				errCh <- fmt.Errorf("no access token in response")
448				return
449			}
450
451			callbackCh <- tokenResponse.AccessToken
452		}()
453
454		// Show success page immediately
455		html := `<!DOCTYPE html>
456<html>
457<head>
458    <title>Curd Authentication</title>
459    <style>
460        body { font-family: Arial, sans-serif; margin: 50px; text-align: center; background: #1a1a1a; color: white; }
461        .loading { color: #2196F3; font-size: 18px; margin-bottom: 20px; }
462    </style>
463</head>
464<body>
465    <div class="loading">Processing authentication...</div>
466    <p>Exchanging authorization code for token. You can close this window.</p>
467</body>
468</html>`
469		fmt.Fprint(w, html)
470	})
471
472	// Start server in background
473	go func() {
474		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
475			errCh <- fmt.Errorf("failed to start server: %w", err)
476		}
477	}()
478	defer srv.Shutdown(ctx)
479
480	// Give server a moment to start
481	time.Sleep(100 * time.Millisecond)
482
483	// Open browser for authentication using Authorization Code Grant flow (response_type=code)
484	authURL := fmt.Sprintf("%s/authorize?client_id=%s&redirect_uri=%s&response_type=code",
485		anilistOAuthURL,
486		anilistClientID,
487		url.QueryEscape(anilistRedirectURI))
488
489	fmt.Println("Opening browser for AniList authentication...")
490	fmt.Printf("If the browser doesn't open automatically, visit: %s\n", authURL)
491
492	if err := browser.OpenURL(authURL); err != nil {
493		fmt.Printf("Failed to open browser automatically: %v\n", err)
494		fmt.Println("Please copy and paste the URL above into your browser")
495	}
496
497	// Wait for token
498	var accessToken string
499	select {
500	case accessToken = <-callbackCh:
501	case err := <-errCh:
502		return "", fmt.Errorf("authentication failed: %w", err)
503	case <-ctx.Done():
504		return "", fmt.Errorf("authentication timeout after 5 minutes")
505	}
506
507	// Create token object and save
508	token := &AnilistToken{
509		AccessToken: accessToken,
510		TokenType:   "Bearer",
511		ExpiresIn:   31536000, // AniList tokens are valid for 1 year
512		ExpiresAt:   time.Now().Add(365 * 24 * time.Hour),
513	}
514
515	// Save token to file
516	if err := saveToken(tokenPath, token); err != nil {
517		return "", fmt.Errorf("failed to save token: %w", err)
518	}
519
520	fmt.Println("Authentication successful!")
521	return token.AccessToken, nil
522}
523
524// loadToken loads the token from the token file
525func loadToken(tokenPath string) (*AnilistToken, error) {
526	data, err := os.ReadFile(tokenPath)
527	if err != nil {
528		return nil, fmt.Errorf("failed to read token file: %w", err)
529	}
530
531	var token AnilistToken
532	if err := json.Unmarshal(data, &token); err != nil {
533		return nil, fmt.Errorf("failed to parse token file: %w", err)
534	}
535
536	return &token, nil
537}
538
539// saveToken saves the token to the token file
540func saveToken(tokenPath string, token *AnilistToken) error {
541	// Ensure directory exists
542	if err := os.MkdirAll(filepath.Dir(tokenPath), 0o755); err != nil {
543		return fmt.Errorf("failed to create directory: %w", err)
544	}
545
546	data, err := json.Marshal(token)
547	if err != nil {
548		return fmt.Errorf("failed to marshal token: %w", err)
549	}
550
551	return os.WriteFile(tokenPath, data, 0o600)
552}
553
554// isTokenValid checks if the token is still valid
555func isTokenValid(token *AnilistToken) bool {
556	return token != nil && token.AccessToken != "" && time.Now().Before(token.ExpiresAt)
557}
558
559// GetTokenFromFile loads the token from the token file (supports both old text format and new JSON format)
560func GetTokenFromFile(tokenPath string) (string, error) {
561	data, err := os.ReadFile(tokenPath)
562	if err != nil {
563		return "", fmt.Errorf("failed to read token from file: %w", err)
564	}
565
566	// Try to parse as JSON first (new format)
567	var token AnilistToken
568	if err := json.Unmarshal(data, &token); err == nil {
569		// It's JSON format, check if token is valid
570		if isTokenValid(&token) {
571			return token.AccessToken, nil
572		}
573		return "", fmt.Errorf("token has expired")
574	}
575
576	// Fall back to plain text format (old format)
577	plainToken := strings.TrimSpace(string(data))
578	if plainToken == "" {
579		return "", fmt.Errorf("empty token file")
580	}
581
582	return plainToken, nil
583}
584
585func ChangeToken(config *CurdConfig, user *User) {
586	var err error
587	tokenPath := filepath.Join(os.ExpandEnv(config.StoragePath), "anilist_token.json")
588
589	// Try browser-based OAuth first
590	fmt.Println("Starting browser-based authentication...")
591	user.Token, err = authenticateWithBrowser(tokenPath)
592	if err != nil {
593		Log("Browser authentication failed: " + err.Error())
594		fmt.Printf("Browser authentication failed: %v\n", err)
595		fmt.Println("Falling back to manual token entry...")
596
597		// Simple CLI fallback
598		fmt.Println("Please visit: https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token&redirect_uri=http://localhost:8000/oauth/callback")
599		fmt.Print("Copy and paste your access token here: ")
600		fmt.Scanln(&user.Token)
601
602		if user.Token == "" {
603			ExitCurd(fmt.Errorf("no token provided"))
604		}
605
606		// Save the manually entered token as JSON format
607		token := &AnilistToken{
608			AccessToken: user.Token,
609			TokenType:   "Bearer",
610			ExpiresIn:   31536000, // AniList tokens are valid for 1 year
611			ExpiresAt:   time.Now().Add(365 * 24 * time.Hour),
612		}
613
614		if err := saveToken(tokenPath, token); err != nil {
615			ExitCurd(fmt.Errorf("failed to save token: %w", err))
616		}
617	}
618
619	if user.Token == "" {
620		ExitCurd(fmt.Errorf("no token provided"))
621	}
622
623	fmt.Println("Token saved successfully!")
624}
625
626// LoadConfigFromFile loads config file from disk into a map (key=value format)
627func LoadConfigFromFile(path string) (map[string]string, error) {
628	file, err := os.Open(path)
629	if err != nil {
630		return nil, err
631	}
632	defer file.Close()
633
634	configMap := make(map[string]string)
635	scanner := bufio.NewScanner(file)
636
637	for scanner.Scan() {
638		line := strings.TrimSpace(scanner.Text())
639		if line == "" || strings.HasPrefix(line, "#") {
640			continue // Skip empty lines and comments
641		}
642
643		parts := strings.SplitN(line, "=", 2)
644		if len(parts) == 2 {
645			key := strings.TrimSpace(parts[0])
646			value := strings.TrimSpace(parts[1])
647			configMap[key] = value
648		}
649	}
650
651	if err := scanner.Err(); err != nil {
652		return nil, err
653	}
654
655	return configMap, nil
656}
657
658// SaveConfigToFile saves updated config map to file in key=value format
659func SaveConfigToFile(path string, configMap map[string]string) error {
660	file, err := os.Create(path)
661	if err != nil {
662		return err
663	}
664	defer file.Close()
665
666	keys := make([]string, 0, len(configMap))
667	for key := range configMap {
668		keys = append(keys, key)
669	}
670	sort.Strings(keys)
671
672	writer := bufio.NewWriter(file)
673	for _, key := range keys {
674		line := fmt.Sprintf("%s=%s\n", key, configMap[key])
675		if _, err := writer.WriteString(line); err != nil {
676			return err
677		}
678	}
679	return writer.Flush()
680}
681
682// PopulateConfig populates the CurdConfig struct from a map
683func PopulateConfig(configMap map[string]string) CurdConfig {
684	config := CurdConfig{}
685	configValue := reflect.ValueOf(&config).Elem()
686	defaults := defaultConfigMap()
687
688	for i := 0; i < configValue.NumField(); i++ {
689		field := configValue.Type().Field(i)
690		tag := field.Tag.Get("config")
691
692		value, exists := configMap[tag]
693		if !exists || value == "" {
694			value = defaults[tag]
695		}
696		fieldValue := configValue.FieldByName(field.Name)
697
698		if fieldValue.CanSet() {
699			switch fieldValue.Kind() {
700			case reflect.String:
701				fieldValue.SetString(value)
702			case reflect.Int:
703				intVal, err := strconv.Atoi(value)
704				if err != nil {
705					intVal, _ = strconv.Atoi(defaults[tag])
706				}
707				fieldValue.SetInt(int64(intVal))
708			case reflect.Bool:
709				boolVal, err := strconv.ParseBool(value)
710				if err != nil {
711					boolVal, _ = strconv.ParseBool(defaults[tag])
712				}
713				fieldValue.SetBool(boolVal)
714			}
715		}
716	}
717
718	// Handle MpvArgs specially
719	if mpvArgs, exists := configMap["MpvArgs"]; exists {
720		config.MpvArgs = parseStringArray(mpvArgs)
721	}
722
723	// Validate PercentageToMarkComplete range (0-100)
724	if config.PercentageToMarkComplete < 0 {
725		config.PercentageToMarkComplete = 0
726	} else if config.PercentageToMarkComplete > 100 {
727		config.PercentageToMarkComplete = 100
728	}
729
730	if config.MpvPlaybackStartTimeout <= 0 {
731		config.MpvPlaybackStartTimeout = DefaultMpvPlaybackStartTimeout
732	} else if config.MpvPlaybackStartTimeout > maxMpvPlaybackStartTimeout {
733		config.MpvPlaybackStartTimeout = maxMpvPlaybackStartTimeout
734	}
735
736	return config
737}
738
739func normalizeRemoteTracker(value string) string {
740	switch strings.ToLower(strings.TrimSpace(value)) {
741	case "", "none", "disabled", "off", "local":
742		return TrackingRemoteNone
743	case "anilist", "ani-list":
744		return TrackingRemoteAniList
745	case "myanimelist", "my_anime_list", "my-anime-list", "mal":
746		return TrackingRemoteMyAnimeList
747	case "anilist+myanimelist", "anilist,myanimelist", "myanimelist+anilist", "myanimelist,anilist", "both", "dual":
748		return TrackingRemoteBoth
749	default:
750		return ""
751	}
752}
753
754func normalizeTrackingConfig(config *CurdConfig) {
755	if config == nil {
756		return
757	}
758
759	remote := normalizeRemoteTracker(config.TrackingRemote)
760	if remote == "" {
761		config.TrackingConfigured = false
762		remote = TrackingRemoteAniList
763	}
764
765	config.TrackingRemote = remote
766	config.TrackingLocal = true
767}
768
769func getOrderedCategories(userCurdConfig *CurdConfig) []SelectionOption {
770	// Define the default categories and all available labels
771	defaultOrder := []string{"CURRENT", "ALL", "UNTRACKED", "UPDATE", "REMAP_PROVIDER", "CONTINUE_LAST", "TRACKER", "PROVIDER"}
772	availableLabels := map[string]string{
773		"CURRENT":        "Currently Watching",
774		"ALL":            "Show All",
775		"UNTRACKED":      "Untracked Watching",
776		"UPDATE":         "Update (Episode, Status, Score)",
777		"REMAP_PROVIDER": "Remap Provider",
778		"CONTINUE_LAST":  "Continue Last Session",
779		"PLANNING":       "Plan to Watch",
780		"COMPLETED":      "Completed",
781		"PAUSED":         "Paused",
782		"DROPPED":        "Dropped",
783		"REWATCHING":     "Rewatching",
784		"TRACKER":        "Change Tracker",
785		"PROVIDER":       "Change Provider",
786	}
787
788	// Create ordered list to store final result
789	finalOrder := make([]string, 0)
790	seen := make(map[string]bool)
791
792	// If no menu order specified, use default order
793	if userCurdConfig.MenuOrder == "" {
794		finalOrder = defaultOrder
795	} else {
796		// Only show items explicitly specified by user
797		menuItems := strings.Split(userCurdConfig.MenuOrder, ",")
798		for _, key := range menuItems {
799			key = strings.TrimSpace(key)
800			if _, exists := availableLabels[key]; exists && !seen[key] {
801				finalOrder = append(finalOrder, key)
802				seen[key] = true
803			}
804		}
805	}
806
807	// Create the final ordered slice of SelectionOptions
808	if !seen["TRACKER"] {
809		finalOrder = append(finalOrder, "TRACKER")
810	}
811	orderedCategories := make([]SelectionOption, 0, len(finalOrder))
812	for _, key := range finalOrder {
813		if !trackingCategoryEnabled(userCurdConfig, key) {
814			continue
815		}
816		orderedCategories = append(orderedCategories, SelectionOption{
817			Key:   key,
818			Label: availableLabels[key],
819		})
820	}
821
822	return orderedCategories
823}