internal/config.go

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