internal/config.go

813 lines · 25216 bytes · executable

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