internal/config.go

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