internal/curd.go

2072 lines · 68088 bytes

29 symbols in this file
   1package internal
   2
   3import (
   4	"crypto/md5"
   5	"encoding/json"
   6	"fmt"
   7	"io"
   8	"net/http"
   9	"os"
  10	"os/exec"
  11	"path/filepath"
  12	"regexp"
  13	"runtime"
  14	"strconv"
  15	"strings"
  16	"time"
  17
  18	"github.com/gen2brain/beeep"
  19	"github.com/pkg/browser"
  20)
  21
  22var alternateScreenActive bool
  23
  24func EditConfig(configFilePath string) {
  25	// Get the user's preferred editor from the EDITOR environment variable
  26	editor := os.Getenv("EDITOR")
  27	if editor == "" {
  28		// If EDITOR is not set, use system-specific defaults
  29		if runtime.GOOS == "windows" {
  30			// Try Notepad++ first
  31			if _, err := exec.LookPath("notepad++"); err == nil {
  32				editor = "notepad++"
  33			} else {
  34				editor = "notepad.exe"
  35			}
  36		} else {
  37			if _, err := exec.LookPath("vim"); err == nil {
  38				editor = "vim"
  39			} else {
  40				editor = "nano"
  41			}
  42		}
  43	}
  44
  45	// Construct the command to open the config file
  46	cmd := exec.Command(editor, configFilePath)
  47
  48	// Set the command to run in the current terminal
  49	cmd.Stdin = os.Stdin
  50	cmd.Stdout = os.Stdout
  51	cmd.Stderr = os.Stderr
  52
  53	// Run the editor command
  54	err := cmd.Run()
  55	if err != nil {
  56		CurdOut(fmt.Sprintf("Error opening config file: %v", err))
  57		return
  58	}
  59
  60	CurdOut("Config file edited successfully.")
  61}
  62
  63// ClearLogFile removes all contents from the specified log file
  64func ClearLogFile(logFile string) error {
  65	if err := os.MkdirAll(filepath.Dir(logFile), 0755); err != nil {
  66		return fmt.Errorf("failed to create log directory: %w", err)
  67	}
  68
  69	// Open the file with truncate flag to clear its contents.
  70	file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
  71	if err != nil {
  72		return fmt.Errorf("failed to open log file: %w", err)
  73	}
  74	defer file.Close()
  75
  76	return nil
  77}
  78
  79// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
  80func Log(data interface{}) error {
  81	logFile := GetGlobalLogFile()
  82	// Open or create the log file
  83	file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
  84	if err != nil {
  85		return err
  86	}
  87	defer file.Close()
  88
  89	// Attempt to marshal the data into JSON
  90	jsonData, err := json.Marshal(data)
  91	if err != nil {
  92		return err
  93	}
  94
  95	// Get the caller information
  96	_, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
  97	if !ok {
  98		return fmt.Errorf("unable to get caller information")
  99	}
 100
 101	// Log the current time and the JSON representation along with caller info
 102	currentTime := time.Now().Format("2006/01/02 15:04:05")
 103	logMessage := fmt.Sprintf("[LOG] %s %s:%d: %s\n", currentTime, filename, lineNumber, jsonData)
 104	_, err = fmt.Fprint(file, logMessage) // Write to the file
 105	if err != nil {
 106		return err
 107	}
 108
 109	return nil
 110}
 111
 112// ClearScreen clears the terminal screen and saves the state
 113func ClearScreen() {
 114	userCurdConfig := GetGlobalConfig()
 115	if userCurdConfig == nil {
 116		return
 117	}
 118
 119	if userCurdConfig.AlternateScreen == false {
 120		return
 121	}
 122
 123	fmt.Print("\033[?1049h") // Switch to alternate screen buffer
 124	fmt.Print("\033[2J")     // Clear the entire screen
 125	fmt.Print("\033[H")      // Move cursor to the top left
 126	alternateScreenActive = true
 127}
 128
 129// RestoreScreen restores the original terminal state
 130func RestoreScreen() {
 131	if !alternateScreenActive {
 132		return
 133	}
 134
 135	fmt.Print("\033[?1049l") // Switch back to the main screen buffer
 136	alternateScreenActive = false
 137}
 138
 139func ExitCurd(err error) {
 140	RestoreScreen()
 141
 142	anime := GetGlobalAnime()
 143	socketPath := ""
 144	if (anime != nil) && (anime.Ep.Player.SocketPath != "") {
 145		socketPath = anime.Ep.Player.SocketPath
 146		_, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
 147		if err != nil {
 148			Log("Error closing MPV: " + err.Error())
 149		}
 150	}
 151
 152	CurdOut("Have a great day!")
 153	// If the error is not about the connection refused, print the error
 154	if err != nil && (socketPath == "" || !strings.Contains(err.Error(), "dial unix "+socketPath+": connect: connection refused")) {
 155		CurdOut(fmt.Sprintf("Error: %v", err))
 156		if runtime.GOOS == "windows" {
 157			fmt.Println("Press Enter to exit")
 158			var wait string
 159			fmt.Scanln(&wait)
 160			exitWithRestore(1)
 161		} else {
 162			exitWithRestore(1)
 163		}
 164	}
 165	exitWithRestore(0)
 166}
 167
 168func CurdOut(data interface{}) {
 169	userCurdConfig := GetGlobalConfig()
 170	if userCurdConfig == nil {
 171		userCurdConfig = &CurdConfig{}
 172	}
 173	if !userCurdConfig.RofiSelection {
 174		fmt.Println(fmt.Sprintf("%v", data))
 175	} else {
 176		switch runtime.GOOS {
 177		case "windows":
 178			err := beeep.Notify(
 179				"Curd",
 180				fmt.Sprintf("%v", data),
 181				"",
 182			)
 183
 184			if err != nil {
 185				Log(fmt.Sprintf("Failed to send notification: %v", err))
 186			}
 187		case "linux":
 188			// Check if the input starts with "-i" for image notification
 189			dataStr := fmt.Sprintf("%v", data)
 190			if strings.HasPrefix(dataStr, "-i") && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
 191				// Split the string to get image path and message
 192				parts := strings.SplitN(dataStr, " ", 3)
 193				if len(parts) == 3 {
 194					// Remove quotes from the message
 195					message := strings.Trim(parts[2], "\"")
 196					cmd := exec.Command("notify-send",
 197						"-a", "Curd",
 198						"-h", "string:x-canonical-private-synchronous:curd-notification",
 199						"Curd",
 200						"-i", parts[1],
 201						message)
 202					err := cmd.Run()
 203					if err != nil {
 204						Log(fmt.Sprintf("%v", cmd))
 205						Log(fmt.Sprintf("Failed to send notification: %v", err))
 206					}
 207				}
 208			} else {
 209				cmd := exec.Command("notify-send",
 210					"-a", "Curd",
 211					"-h", "string:x-canonical-private-synchronous:curd-notification",
 212					"Curd",
 213					dataStr)
 214				err := cmd.Run()
 215				if err != nil {
 216					Log(fmt.Sprintf("%v", cmd))
 217					Log(fmt.Sprintf("Failed to send notification: %v", err))
 218				}
 219			}
 220		}
 221	}
 222}
 223
 224func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
 225	if !UsesRemoteTracking(userCurdConfig) {
 226		CurdOut("Remote tracking is disabled in your config.")
 227		return
 228	}
 229
 230	// Create update options
 231	updateOptions := []SelectionOption{
 232		{Key: "CATEGORY", Label: "Change Anime Category"},
 233		{Key: "PROGRESS", Label: "Change Progress"},
 234		{Key: "SCORE", Label: "Add/Change Score"},
 235	}
 236
 237	// Navigation loop for update option selection
 238updateOptionLoop:
 239	for {
 240		// Select update option
 241		updateSelection, err := DynamicSelect(updateOptions)
 242		if err != nil {
 243			Log(fmt.Sprintf("Failed to select update option: %v", err))
 244			ExitCurd(fmt.Errorf("Failed to select update option"))
 245		}
 246
 247		if updateSelection.Key == "-1" {
 248			ExitCurd(nil)
 249		}
 250
 251		// Back from update selection returns to home menu
 252		if updateSelection.Key == "-2" {
 253			return // Return to caller (home menu)
 254		}
 255
 256		// Get user's anime list
 257		var animeListOptions []SelectionOption
 258		var animeListMapPreview map[string]RofiSelectPreview
 259
 260		if user.ListSync != nil {
 261			user.AnimeList = user.ListSync.Current()
 262		}
 263
 264		if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 265			animeListMapPreview = buildCategoryPreviewOptions(user.AnimeList, "ALL")
 266		} else {
 267			animeListOptions = buildCategorySelectionOptions(user.AnimeList, "ALL")
 268		}
 269
 270		// Anime selection loop
 271	animeSelectLoop:
 272		for {
 273			// Select anime to update
 274			var selectedAnime SelectionOption
 275			if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 276				selectedAnime, err = DynamicSelectPreviewWithRefresh(animeListMapPreview, false, &PreviewSelectionRefreshConfig{
 277					Updates: user.ListSync.Updates(),
 278					BuildOptions: func(list AnimeList) map[string]RofiSelectPreview {
 279						return buildCategoryPreviewOptions(list, "ALL")
 280					},
 281				})
 282			} else {
 283				selectedAnime, err = DynamicSelectWithRefresh(animeListOptions, &SelectionRefreshConfig{
 284					Updates: user.ListSync.Updates(),
 285					BuildOptions: func(list AnimeList) []SelectionOption {
 286						return buildCategorySelectionOptions(list, "ALL")
 287					},
 288				})
 289			}
 290			if err != nil {
 291				Log(fmt.Sprintf("Failed to select anime: %v", err))
 292				ExitCurd(fmt.Errorf("Failed to select anime"))
 293			}
 294
 295			if selectedAnime.Key == "-1" {
 296				ExitCurd(nil)
 297			}
 298
 299			// Back from anime selection goes to update option selection
 300			if selectedAnime.Key == "-2" {
 301				ClearScreen()
 302				continue updateOptionLoop
 303			}
 304
 305			animeID, err := strconv.Atoi(selectedAnime.Key)
 306			if err != nil {
 307				Log(fmt.Sprintf("Failed to convert anime ID: %v", err))
 308				ExitCurd(fmt.Errorf("Failed to convert anime ID"))
 309			}
 310
 311			if user.ListSync != nil {
 312				user.AnimeList = user.ListSync.Current()
 313			}
 314
 315			// After getting animeID, get the current anime entry
 316			selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key)
 317			if err != nil {
 318				Log(fmt.Sprintf("Can not find the anime in tracked anime list: %v", err))
 319				ExitCurd(fmt.Errorf("Can not find the anime in tracked anime list"))
 320			}
 321			ClearScreen()
 322
 323			// Final selection loop (for category/progress/score)
 324			for {
 325				switch updateSelection.Key {
 326				case "CATEGORY":
 327					categories := []SelectionOption{
 328						{Key: "CURRENT", Label: "Currently Watching"},
 329						{Key: "COMPLETED", Label: "Completed"},
 330						{Key: "PAUSED", Label: "On Hold"},
 331						{Key: "DROPPED", Label: "Dropped"},
 332						{Key: "PLANNING", Label: "Plan to Watch"},
 333						{Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
 334					}
 335
 336					currentStatus := "None"
 337					if selectedAnilistAnime.Status != "" {
 338						// Find the label for the current status
 339						for _, cat := range categories {
 340							if cat.Key == selectedAnilistAnime.Status {
 341								currentStatus = cat.Label
 342								break
 343							}
 344						}
 345					}
 346					CurdOut(fmt.Sprintf("Current category: %s", currentStatus))
 347
 348					categorySelection, err := DynamicSelect(categories)
 349					if err != nil {
 350						Log(fmt.Sprintf("Failed to select category: %v", err))
 351						ExitCurd(fmt.Errorf("Failed to select category"))
 352					}
 353
 354					if categorySelection.Key == "-1" {
 355						ExitCurd(nil)
 356					}
 357
 358					// Back from category selection goes to anime selection
 359					if categorySelection.Key == "-2" {
 360						ClearScreen()
 361						continue animeSelectLoop
 362					}
 363
 364					err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
 365					if err != nil {
 366						Log(fmt.Sprintf("Failed to update anime status: %v", err))
 367						ExitCurd(fmt.Errorf("Failed to update anime status"))
 368					}
 369
 370				case "PROGRESS":
 371					currentProgress := "None"
 372					if selectedAnilistAnime.Progress > 0 {
 373						currentProgress = strconv.Itoa(selectedAnilistAnime.Progress)
 374					}
 375
 376					var progress string
 377					if userCurdConfig.RofiSelection {
 378						progress, err = GetUserInputFromRofi(fmt.Sprintf("Current progress: %s - Enter new progress (episode number)", currentProgress))
 379						if err != nil {
 380							Log(fmt.Sprintf("Failed to get progress input: %v", err))
 381							ExitCurd(fmt.Errorf("Failed to get progress input"))
 382						}
 383					} else {
 384						CurdOut(fmt.Sprintf("Current progress: %s", currentProgress))
 385						CurdOut("Enter new progress (episode number):")
 386						fmt.Scanln(&progress)
 387					}
 388
 389					progressNum, err := parseNonNegativeIntInput(progress, "progress")
 390					if err != nil {
 391						Log(fmt.Sprintf("Failed to convert progress to number: %v", err))
 392						ExitCurd(fmt.Errorf("Failed to convert progress to number"))
 393					}
 394
 395					err = UpdateAnimeProgress(user.Token, animeID, progressNum)
 396					if err != nil {
 397						Log(fmt.Sprintf("Failed to update anime progress: %v", err))
 398						ExitCurd(fmt.Errorf("Failed to update anime progress"))
 399					}
 400
 401				case "SCORE":
 402					currentScore := "None"
 403					if selectedAnilistAnime.Score > 0 {
 404						currentScore = strconv.Itoa(int(selectedAnilistAnime.Score))
 405					}
 406					CurdOut(fmt.Sprintf("Current score: %s", currentScore))
 407
 408					err = RateAnime(user.Token, animeID)
 409					if err != nil {
 410						Log(fmt.Sprintf("Failed to update anime score: %v", err))
 411						ExitCurd(fmt.Errorf("Failed to update anime score"))
 412					}
 413				}
 414
 415				if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
 416					Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
 417					ExitCurd(fmt.Errorf("Failed to refresh anime list"))
 418				}
 419
 420				CurdOut("Anime updated successfully!")
 421				return
 422			}
 423		}
 424	}
 425}
 426
 427func UpdateCurd(repo, fileName string) error {
 428	// Get the path of the currently running executable
 429	executablePath, err := os.Executable()
 430	if err != nil {
 431		return fmt.Errorf("unable to find current executable: %v", err)
 432	}
 433	// Resolve symlinks so we replace the real binary (e.g. /usr/local/bin/curd).
 434	if resolved, resolveErr := filepath.EvalSymlinks(executablePath); resolveErr == nil && resolved != "" {
 435		executablePath = resolved
 436	}
 437
 438	binaryName, err := curdReleaseBinaryName()
 439	if err != nil {
 440		return err
 441	}
 442	_ = fileName // retained for call-site compatibility
 443
 444	if strings.TrimSpace(repo) == "" {
 445		repo = defaultUpdateRepo
 446	}
 447	// GitHub release URL for curd
 448	url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName)
 449
 450	// Prefer a temp file next to the executable (same filesystem → atomic rename).
 451	// Fall back to OS temp dir when the install dir is not writable (e.g. /usr/bin).
 452	tmpPath, out, err := createUpdateTempFile(executablePath, binaryName)
 453	if err != nil {
 454		return fmt.Errorf("failed to create temporary file: %v", err)
 455	}
 456
 457	// Download the curd executable
 458	client := sharedHTTPClient
 459	if client == nil {
 460		client = &http.Client{Timeout: 5 * time.Minute}
 461	}
 462	resp, err := client.Get(url)
 463	if err != nil {
 464		out.Close()
 465		_ = os.Remove(tmpPath)
 466		return fmt.Errorf("failed to download file: %v", err)
 467	}
 468	defer resp.Body.Close()
 469
 470	// Check if the download was successful
 471	if resp.StatusCode != http.StatusOK {
 472		out.Close()
 473		_ = os.Remove(tmpPath)
 474		return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
 475	}
 476
 477	// Copy the downloaded content to the temporary file
 478	if _, err := io.Copy(out, resp.Body); err != nil {
 479		out.Close()
 480		_ = os.Remove(tmpPath)
 481		return fmt.Errorf("failed to write to temporary file: %v", err)
 482	}
 483	if err := out.Chmod(0755); err != nil {
 484		out.Close()
 485		_ = os.Remove(tmpPath)
 486		return fmt.Errorf("failed to set file permissions: %v", err)
 487	}
 488	if err := out.Close(); err != nil {
 489		_ = os.Remove(tmpPath)
 490		return fmt.Errorf("failed to close temporary file: %v", err)
 491	}
 492
 493	// Replace the old executable (prompts for sudo if the install path is not writable).
 494	if err := replaceExecutable(tmpPath, executablePath); err != nil {
 495		_ = os.Remove(tmpPath)
 496		return err
 497	}
 498	return nil
 499}
 500
 501func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
 502	var query string
 503	// Remove the redeclared variable declaration since animeOptions is already declared above
 504	var animeMapPreview map[string]RofiSelectPreview
 505	var animeOptions []SelectionOption
 506	var err error
 507	var anilistSelectedOption SelectionOption
 508
 509	query, err = promptText(userCurdConfig, "Enter the anime name", false)
 510	if err != nil {
 511		Log("Error getting user input: " + err.Error())
 512		ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
 513	}
 514	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 515		animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
 516	} else {
 517		animeOptions, err = SearchAnimeAnilist(query, user.Token)
 518		if err != nil {
 519			Log(fmt.Sprintf("Failed to search anime: %v", err))
 520			ExitCurd(fmt.Errorf("Failed to search anime"))
 521		}
 522	}
 523	if err != nil {
 524		Log(fmt.Sprintf("Failed to search anime: %v", err))
 525		ExitCurd(fmt.Errorf("Failed to search anime"))
 526	}
 527	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 528		anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
 529	} else {
 530		anilistSelectedOption, err = DynamicSelect(animeOptions)
 531	}
 532	if err != nil {
 533		Log(fmt.Sprintf("No anime available: %v", err))
 534		ExitCurd(fmt.Errorf("No anime available"))
 535	}
 536
 537	if anilistSelectedOption.Key == "-1" {
 538		ExitCurd(nil)
 539	}
 540
 541	// Handle back button - return to caller
 542	if anilistSelectedOption.Key == "-2" {
 543		return SelectionOption{Key: "-2", Label: "Back"}
 544	}
 545
 546	animeID, err := strconv.Atoi(anilistSelectedOption.Key)
 547	if err != nil {
 548		Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err))
 549		ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
 550	}
 551
 552	if !UsesRemoteTracking(userCurdConfig) {
 553		return anilistSelectedOption
 554	}
 555
 556	// Add category selection before adding to list
 557	categories := []SelectionOption{
 558		{Key: "CURRENT", Label: "Currently Watching"},
 559		{Key: "COMPLETED", Label: "Completed"},
 560		{Key: "PAUSED", Label: "On Hold"},
 561		{Key: "DROPPED", Label: "Dropped"},
 562		{Key: "PLANNING", Label: "Plan to Watch"},
 563		{Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
 564	}
 565
 566	ClearScreen()
 567	CurdOut("Select which list to add the anime to:")
 568
 569	categorySelection, err := DynamicSelect(categories)
 570	if err != nil {
 571		Log(fmt.Sprintf("Failed to select category: %v", err))
 572		ExitCurd(fmt.Errorf("Failed to select category"))
 573	}
 574
 575	if categorySelection.Key == "-1" {
 576		ExitCurd(nil)
 577	}
 578
 579	// Handle back button - return to caller
 580	if categorySelection.Key == "-2" {
 581		return SelectionOption{Key: "-2", Label: "Back"}
 582	}
 583
 584	err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
 585	if err != nil {
 586		Log(fmt.Sprintf("Failed to add anime to list: %v", err))
 587		ExitCurd(fmt.Errorf("Failed to add anime to list"))
 588	}
 589
 590	if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
 591		Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
 592		ExitCurd(fmt.Errorf("Failed to refresh anime list"))
 593	}
 594
 595	return anilistSelectedOption
 596}
 597
 598func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) {
 599	var err error
 600	var startingRewatch bool
 601
 602	// Filter anime list based on selected category
 603	var animeListOptions []SelectionOption
 604	var animeListMapPreview map[string]RofiSelectPreview
 605
 606	// Initialize anime list. On a cache hit this is instant (reads from disk) and
 607	// the user ID is seeded from the cached payload, avoiding a blocking network
 608	// round-trip to AniList. The real user ID + latest list are refreshed in the
 609	// background goroutine inside InitializeUserAnimeList.
 610	if err := InitializeUserAnimeList(userCurdConfig, user); err != nil {
 611		Log(fmt.Sprintf("Failed to initialize anime list: %v", err))
 612		ExitCurd(fmt.Errorf("Failed to get user data\nYou can reset the token by running `curd -change-token`"))
 613	}
 614
 615	// Variables for selection results (used in both branches and after)
 616	var anilistSelectedOption SelectionOption
 617	var selectedAllanimeAnime SelectionOption
 618	var userQuery string
 619	_ = selectedAllanimeAnime // Used later in the function
 620
 621	// Navigation loop for the entire setup process
 622	for {
 623		startingRewatch = false
 624
 625		// If continueLast flag is set, directly get the last watched anime
 626		if anime.Ep.ContinueLast {
 627			// Get the last anime ID from the curd_id file
 628			idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
 629			idBytes, err := os.ReadFile(idFilePath)
 630			if err != nil {
 631				Log("Error reading curd_id file: " + err.Error())
 632				ExitCurd(fmt.Errorf("No last watched anime found"))
 633			}
 634
 635			anilistID, err := strconv.Atoi(string(idBytes))
 636			if err != nil {
 637				Log("Error converting anilist ID: " + err.Error())
 638				ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
 639			}
 640
 641			// Find the anime in database
 642			animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
 643			if animePointer == nil {
 644				ExitCurd(fmt.Errorf("Last watched anime not found in database"))
 645			}
 646
 647			// Set the anime details
 648			anime.AnilistId = animePointer.AnilistId
 649			anilistSelectedOption.Key = strconv.Itoa(animePointer.AnilistId)
 650			// anime.ProviderId = animePointer.ProviderId
 651			// anime.Title = animePointer.Title
 652			// anime.Ep.Number = animePointer.Ep.Number
 653			// anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
 654			// anime.Ep.Resume = true
 655
 656		} else {
 657			// Navigation loop for category and anime selection
 658		categorySelectionLoop:
 659			for {
 660				// Skip category selection if Current flag is set
 661				var categorySelection SelectionOption
 662				if userCurdConfig.CurrentCategory {
 663					categorySelection = SelectionOption{
 664						Key:   "CURRENT",
 665						Label: "Currently Watching",
 666					}
 667				} else {
 668					// Create category selection map
 669					// Get ordered categories
 670					orderedCategories := getOrderedCategories(userCurdConfig)
 671
 672					// Use DynamicSelect with ordered categories directly
 673					categorySelection, err = DynamicSelect(orderedCategories)
 674
 675					if err != nil {
 676						Log(fmt.Sprintf("Failed to select category: %v", err))
 677						ExitCurd(fmt.Errorf("Failed to select category"))
 678					}
 679
 680					categorySelection = NormalizeSelectionKey(categorySelection)
 681					if SelectionMeansQuit(categorySelection) {
 682						ExitCurd(nil)
 683					}
 684
 685					if SelectionMeansBack(categorySelection) {
 686						continue
 687					}
 688					if categorySelection.Key == "" {
 689						// Empty/cancelled selection — re-show category menu.
 690						continue
 691					}
 692
 693					// Handle options
 694					if categorySelection.Key == "PROVIDER" {
 695						ClearScreen()
 696						ChangeProvider(userCurdConfig)
 697						ClearScreen()
 698						continue categorySelectionLoop
 699					} else if categorySelection.Key == "TRACKER" {
 700						ClearScreen()
 701						ChangeTracker(userCurdConfig, user)
 702						ClearScreen()
 703						continue categorySelectionLoop
 704					} else if categorySelection.Key == "UPDATE" {
 705						ClearScreen()
 706						UpdateAnimeEntry(userCurdConfig, user)
 707						// If UpdateAnimeEntry returns, user pressed back - continue to category selection
 708						ClearScreen()
 709						continue categorySelectionLoop
 710					} else if categorySelection.Key == "UNTRACKED" {
 711						ClearScreen()
 712						WatchUntracked(userCurdConfig)
 713						// If WatchUntracked returns, user pressed back OR watched is done- continue to category selection
 714						ClearScreen()
 715						continue categorySelectionLoop
 716					} else if categorySelection.Key == "REMAP_PROVIDER" {
 717						ClearScreen()
 718						RemapProviderAnime(userCurdConfig, user, databaseAnimes)
 719						ClearScreen()
 720						continue categorySelectionLoop
 721					} else if categorySelection.Key == "CONTINUE_LAST" {
 722						anime.Ep.ContinueLast = true
 723					}
 724
 725					ClearScreen()
 726				}
 727
 728				if user.ListSync != nil {
 729					user.AnimeList = user.ListSync.Current()
 730				}
 731
 732				if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 733					animeListMapPreview = buildCategoryPreviewOptions(user.AnimeList, categorySelection.Key)
 734				} else {
 735					animeListOptions = buildCategorySelectionOptions(user.AnimeList, categorySelection.Key)
 736				}
 737
 738				// Anime selection loop (for back navigation)
 739			animeSelectionLoop:
 740				for {
 741					if anime.Ep.ContinueLast {
 742						// Get the last watched anime ID from the curd_id file
 743						curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
 744						curdIDBytes, err := os.ReadFile(curdIDPath)
 745						if err != nil {
 746							Log(fmt.Sprintf("Error reading curd_id file: %v", err))
 747							ExitCurd(fmt.Errorf("Error reading curd_id file"))
 748						}
 749
 750						lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
 751						if err != nil {
 752							Log(fmt.Sprintf("Error converting curd_id to integer: %v", err))
 753							ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
 754						}
 755
 756						anime.AnilistId = lastWatchedID
 757						anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
 758						break categorySelectionLoop
 759					}
 760
 761					// Select anime to watch (Anilist)
 762					var err error
 763					if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 764						anilistSelectedOption, err = DynamicSelectPreviewWithRefresh(animeListMapPreview, true, &PreviewSelectionRefreshConfig{
 765							Updates: user.ListSync.Updates(),
 766							BuildOptions: func(list AnimeList) map[string]RofiSelectPreview {
 767								return buildCategoryPreviewOptions(list, categorySelection.Key)
 768							},
 769						})
 770					} else {
 771						// Add "Add new anime" option to the slice
 772						tempOptions := make([]SelectionOption, len(animeListOptions))
 773						copy(tempOptions, animeListOptions)
 774
 775						tempOptions = append(tempOptions, SelectionOption{
 776							Key:   "add_new",
 777							Label: "Add new anime",
 778						})
 779
 780						anilistSelectedOption, err = DynamicSelectWithRefresh(tempOptions, &SelectionRefreshConfig{
 781							Updates: user.ListSync.Updates(),
 782							BuildOptions: func(list AnimeList) []SelectionOption {
 783								updatedOptions := buildCategorySelectionOptions(list, categorySelection.Key)
 784
 785								updatedOptions = append(updatedOptions, SelectionOption{
 786									Key:   "add_new",
 787									Label: "Add new anime",
 788								})
 789								return updatedOptions
 790							},
 791						})
 792					}
 793					if err != nil {
 794						Log(fmt.Sprintf("Error selecting anime: %v", err))
 795						ExitCurd(fmt.Errorf("Error selecting anime"))
 796					}
 797
 798					Log(anilistSelectedOption)
 799
 800					anilistSelectedOption = NormalizeSelectionKey(anilistSelectedOption)
 801					if SelectionMeansQuit(anilistSelectedOption) {
 802						ExitCurd(nil)
 803					}
 804
 805					// Handle back navigation - go back to category selection
 806					if SelectionMeansBack(anilistSelectedOption) {
 807						if userCurdConfig.CurrentCategory {
 808							// If CurrentCategory is forced, back means quit
 809							ExitCurd(nil)
 810						}
 811						ClearScreen()
 812						continue categorySelectionLoop
 813					}
 814					if anilistSelectedOption.Key == "" {
 815						continue animeSelectionLoop
 816					}
 817
 818					if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
 819						addResult := AddNewAnime(userCurdConfig, anime, user, databaseAnimes)
 820						if addResult.Key == "-2" {
 821							// Back from add new anime goes to anime selection
 822							ClearScreen()
 823							continue animeSelectionLoop
 824						}
 825						anilistSelectedOption = addResult
 826					}
 827
 828					anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
 829					if err != nil {
 830						Log(fmt.Sprintf("Error converting Anilist ID: %v", err))
 831						ExitCurd(fmt.Errorf("Error converting Anilist ID"))
 832					}
 833
 834					// Successfully selected anime, break out of both loops
 835					break categorySelectionLoop
 836				}
 837			}
 838		}
 839		// Wait for the background refresh goroutine to finish before reading
 840		// progress+1. RefreshDone() is a channel that is closed (broadcast) the
 841		// instant the goroutine completes — no polling, no race with the UI
 842		// Updates consumer that already drained the updates channel.
 843		if user.ListSync != nil {
 844			select {
 845			case <-user.ListSync.RefreshDone():
 846				Log("Background refresh done, using latest anime list for playback")
 847			case <-time.After(10 * time.Second):
 848				Log("Timed out waiting for background anime list refresh; using cached list")
 849			}
 850			user.AnimeList = user.ListSync.Current()
 851		}
 852
 853		animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
 854
 855		// Get anime entry
 856		selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
 857		if err != nil {
 858			if UsesRemoteTracking(userCurdConfig) {
 859				Log(fmt.Sprintf("Can not find the anime in tracked anime list: %v", err))
 860				ExitCurd(fmt.Errorf("Can not find the anime in tracked anime list"))
 861			}
 862
 863			fallbackAnime, fallbackErr := GetAnimeDataByID(anime.AnilistId, "")
 864			if fallbackErr != nil {
 865				Log(fmt.Sprintf("Failed to fetch fallback anime data: %v", fallbackErr))
 866				ExitCurd(fmt.Errorf("Failed to get anime data"))
 867			}
 868
 869			selectedAnilistAnime = &Entry{
 870				Media: Media{
 871					ID:       fallbackAnime.AnilistId,
 872					MalID:    fallbackAnime.MalId,
 873					Episodes: fallbackAnime.TotalEpisodes,
 874					Title:    fallbackAnime.Title,
 875					Status:   "FINISHED",
 876				},
 877				Progress:   0,
 878				Status:     "CURRENT",
 879				CoverImage: fallbackAnime.CoverImage,
 880			}
 881		}
 882
 883		if selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED" {
 884			handleUnreleasedAnime(userCurdConfig, user, anime, *selectedAnilistAnime)
 885			ClearScreen()
 886			continue
 887		}
 888
 889		// Set anime entry
 890		anime.Title = selectedAnilistAnime.Media.Title
 891		anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
 892		anime.CoverImage = selectedAnilistAnime.CoverImage
 893		if selectedAnilistAnime.Media.MalID != 0 {
 894			anime.MalId = selectedAnilistAnime.Media.MalID
 895		}
 896		if anime.MalId == 0 {
 897			anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
 898		}
 899		anime.IsAiring = selectedAnilistAnime.Media.Status == "RELEASING" || selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED"
 900		anime.Rewatching = selectedAnilistAnime.Status == "REPEATING"
 901		anime.Repeat = selectedAnilistAnime.Repeat
 902		anime.StartedAt = selectedAnilistAnime.StartedAt
 903		anime.CompletedAt = selectedAnilistAnime.CompletedAt
 904		anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
 905		userQuery = anime.Title.Romaji
 906
 907		if selectedAnilistAnime.Status == "COMPLETED" {
 908			CurdOut("This anime is completed. Start rewatch from episode 1? Continue without updating tracker? Open details?")
 909			selectedOption, err := promptSelect([]SelectionOption{
 910				{Key: "rewatch", Label: "Start rewatch from episode 1"},
 911				{Key: "continue", Label: "Continue without updating tracker"},
 912				{Key: "details", Label: "Open details"},
 913			})
 914			if err != nil {
 915				Log(fmt.Sprintf("Error in completed anime prompt: %v", err))
 916				ExitCurd(fmt.Errorf("Failed to select completed anime action"))
 917			}
 918
 919			switch selectedOption.Key {
 920			case "rewatch":
 921				err = StartAnimeRewatch(user.Token, *anime)
 922				if err != nil {
 923					Log(fmt.Sprintf("Error starting anime rewatch: %v", err))
 924					ExitCurd(fmt.Errorf("Failed to move anime to rewatching"))
 925				}
 926
 927				anime.Rewatching = true
 928				anime.SkipRemoteSync = false
 929				anime.Ep.Number = 1
 930				anime.Ep.Player.PlaybackTime = 0
 931				anime.Ep.Resume = false
 932				startingRewatch = true
 933				CurdOut("Moved anime to Rewatching and restarting from episode 1.")
 934
 935				if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
 936					Log("Error refreshing anime list: " + err.Error())
 937					ExitCurd(err)
 938				}
 939			case "continue":
 940				anime.Rewatching = false
 941				anime.SkipRemoteSync = true
 942				anime.Ep.Number = 1
 943				anime.Ep.Player.PlaybackTime = 0
 944				anime.Ep.Resume = false
 945				startingRewatch = true
 946				CurdOut("Starting episode 1 without updating your tracker.")
 947			case "details":
 948				url := fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId)
 949				CurdOut(fmt.Sprintf("Opening %s", url))
 950				if err := browser.OpenURL(url); err != nil {
 951					Log(fmt.Sprintf("Error opening browser: %v", err))
 952					CurdOut("Failed to open browser.")
 953				}
 954				anime.Ep.ContinueLast = false
 955				continue
 956			case "-1":
 957				ExitCurd(nil)
 958			default:
 959				anime.Ep.ContinueLast = false
 960				continue
 961			}
 962		}
 963
 964		// Check if we need to research provider ID
 965		needsProviderSearch := false
 966		if animePointer == nil {
 967			needsProviderSearch = true
 968		} else if animePointer.ProviderId == "" {
 969			needsProviderSearch = true
 970		} else if animePointer.ProviderName != "" && !ProviderStackContains(userCurdConfig, animePointer.ProviderName) {
 971			needsProviderSearch = true
 972		}
 973
 974		// if anime not found in database or provider changed, find it in animeList
 975		if needsProviderSearch {
 976			Log("Anime not found in database for current provider, searching in animeList...")
 977			mappingOutcome, mappingErr := ResolveAnimeProviderMapping(userCurdConfig, anime, string(userQuery), selectedAnilistAnime)
 978			if mappingErr != nil {
 979				Log(fmt.Sprintf("Provider mapping failed: %v", mappingErr))
 980				ExitCurd(mappingErr)
 981			}
 982			switch mappingOutcome {
 983			case ProviderMappingBack:
 984				CurdOut("Going back to main menu...")
 985				RestoreScreen()
 986				if anime.Ep.ContinueLast {
 987					anime.Ep.ContinueLast = false
 988				}
 989				continue
 990			case ProviderMappingQuit:
 991				ExitCurd(nil)
 992			}
 993		}
 994
 995		// if anime found in database, use its playback state
 996		if animePointer != nil {
 997			if !needsProviderSearch {
 998				anime.ProviderId = animePointer.ProviderId
 999				anime.ProviderName = animePointer.ProviderName
1000			}
1001			anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
1002			if anime.Ep.Number == animePointer.Ep.Number {
1003				anime.Ep.Resume = true
1004			}
1005
1006			// If local history episode is ahead of AniList upstream, prompt user
1007			anilistEpisode := nextEpisodeFromProgress(selectedAnilistAnime.Progress)
1008			if animePointer.Ep.Number > anilistEpisode {
1009				trackerLabel := RemoteTrackingDisplayName(userCurdConfig)
1010				Log(fmt.Sprintf("Local history episode (%d) is ahead of %s episode (%d), prompting user", animePointer.Ep.Number, trackerLabel, anilistEpisode))
1011				options := []SelectionOption{
1012					{Key: "update_upstream", Label: fmt.Sprintf("Use Curd episode %d", animePointer.Ep.Number)},
1013					{Key: "use_anilist", Label: fmt.Sprintf("Use %s episode %d", trackerLabel, anilistEpisode)},
1014				}
1015				CurdOut(fmt.Sprintf("Curd has episode %d. %s has episode %d. Pick one.", animePointer.Ep.Number, trackerLabel, anilistEpisode))
1016				selectedOption, err := DynamicSelect(options)
1017				if err != nil {
1018					Log("Error in episode conflict selection: " + err.Error())
1019				} else if selectedOption.Key == "-1" {
1020					ExitCurd(nil)
1021				} else if selectedOption.Key == "update_upstream" {
1022					// Update remote progress to match local history (progress = local ep - 1, since local ep is "next to watch")
1023					progressToUpdate := animePointer.Ep.Number - 1
1024					if err := UpdateAnimeProgress(user.Token, anime.AnilistId, progressToUpdate); err != nil {
1025						Log(fmt.Sprintf("Error updating %s progress to %d: %v", trackerLabel, progressToUpdate, err))
1026					} else {
1027						Log(fmt.Sprintf("Updated %s progress to %d", trackerLabel, progressToUpdate))
1028					}
1029					anime.Ep.Number = animePointer.Ep.Number
1030					anime.Ep.Resume = true
1031				} else if selectedOption.Key == "use_anilist" {
1032					// Use remote next-episode number (already set from selectedAnilistAnime.Progress + 1)
1033					anime.Ep.Number = anilistEpisode
1034					anime.Ep.Player.PlaybackTime = 0
1035					anime.Ep.Resume = false
1036				}
1037			} else {
1038				anime.Ep.Number = animePointer.Ep.Number
1039			}
1040		}
1041
1042		if startingRewatch {
1043			anime.Ep.Player.PlaybackTime = 0
1044			anime.Ep.Resume = false
1045		}
1046
1047		if selectedAllanimeAnime.Key == "-1" {
1048			ExitCurd(nil)
1049		}
1050
1051		// If anime is not in watching list, prompt user to add it into watching list
1052		isInWatchingList := false
1053		for _, entry := range user.AnimeList.Watching {
1054			if entry.Media.ID == anime.AnilistId {
1055				isInWatchingList = true
1056				break
1057			}
1058		}
1059		if !isInWatchingList {
1060			for _, entry := range user.AnimeList.Rewatching {
1061				if entry.Media.ID == anime.AnilistId {
1062					isInWatchingList = true
1063					break
1064				}
1065			}
1066		}
1067		if anime.Rewatching {
1068			isInWatchingList = true
1069		}
1070
1071		if ShouldWriteRemoteTracking(userCurdConfig, anime) && !isInWatchingList {
1072			// Create options for the prompt
1073			options := []SelectionOption{
1074				{Key: "yes", Label: "Add to watching list"},
1075				{Key: "no", Label: "Continue without adding"},
1076			}
1077
1078			var selectedOption SelectionOption
1079			var err error
1080
1081			// Use rofi for selection
1082			selectedOption, err = DynamicSelect(options)
1083			if err != nil {
1084				Log("Error in selection: " + err.Error())
1085				ExitCurd(err)
1086			}
1087
1088			if selectedOption.Key == "yes" {
1089				err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
1090				if err != nil {
1091					Log("Error adding anime to watching list: " + err.Error())
1092					ExitCurd(err)
1093				}
1094				if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
1095					Log("Error refreshing anime list: " + err.Error())
1096					ExitCurd(err)
1097				}
1098			} else if selectedOption.Key == "-1" {
1099				ExitCurd(nil)
1100			} else if selectedOption.Key == "-2" {
1101				// Handle back button - go back to main menu
1102				CurdOut("Going back to main menu...")
1103				RestoreScreen()
1104				// If we were continuing last, disable it so we go to menu next loop
1105				if anime.Ep.ContinueLast {
1106					anime.Ep.ContinueLast = false
1107				}
1108				continue
1109			}
1110		}
1111
1112		// If upstream is ahead, update the episode number
1113		if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
1114			upstreamNextEpisode := nextEpisodeFromProgress(temp_anime.Progress)
1115			if upstreamNextEpisode > anime.Ep.Number {
1116				anime.Ep.Number = upstreamNextEpisode
1117				anime.Ep.Player.PlaybackTime = 0
1118				anime.Ep.Resume = false
1119			}
1120		}
1121
1122		if anime.TotalEpisodes == 0 {
1123			// Get updated anime data
1124			Log(selectedAllanimeAnime)
1125			updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
1126			Log(updatedAnime)
1127			if err != nil {
1128				Log(fmt.Sprintf("Error getting updated anime data: %v", err))
1129			} else {
1130				anime.TotalEpisodes = updatedAnime.TotalEpisodes
1131				Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
1132			}
1133		}
1134
1135		if anime.TotalEpisodes == 0 { // If failed to get anime data
1136			CurdOut("AniList/MAL did not return total episodes. Attempting to retrieve from provider episode list.")
1137			providerName, providerID := AnimeProviderID(anime)
1138			providerTotal, err := GetProviderTotalEpisodes(QualifyProviderID(providerName, providerID), userCurdConfig.SubOrDub)
1139			if err != nil {
1140				Log(fmt.Sprintf("Failed to retrieve total episodes from provider episode list: %v", err))
1141			} else {
1142				anime.TotalEpisodes = providerTotal
1143				CurdOut(fmt.Sprintf("Retrieved total episodes from provider: %d", anime.TotalEpisodes))
1144			}
1145		}
1146
1147		if anime.TotalEpisodes == 0 { // If the mapped provider alone couldn't provide a total
1148			CurdOut("Attempting to determine total episodes from the full provider stack.")
1149			totalQuery := animeSearchTitle(anime)
1150			if strings.TrimSpace(totalQuery) == "" {
1151				totalQuery = string(userQuery)
1152			}
1153			stackTotal, stackErr := determineProviderTotalEpisodes(userCurdConfig, totalQuery, anime, userCurdConfig.SubOrDub)
1154			if stackErr != nil {
1155				Log(fmt.Sprintf("Failed to determine total episodes from provider stack: %v", stackErr))
1156			} else {
1157				anime.TotalEpisodes = stackTotal
1158				CurdOut(fmt.Sprintf("Retrieved total episodes from provider stack: %d", anime.TotalEpisodes))
1159			}
1160		}
1161
1162		if anime.TotalEpisodes == 0 { // If provider episode list did not have a usable total
1163			CurdOut("Attempting to retrieve total episodes from anime search results.")
1164			animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
1165			if err != nil {
1166				CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
1167			} else {
1168				for _, option := range animeList {
1169					optionProviderName, optionProviderID, ok := ParseProviderQualifiedID(option.Key)
1170					if !ok {
1171						optionProviderName = configuredProviderNames(userCurdConfig)[0]
1172						optionProviderID = option.Key
1173					}
1174					if optionProviderID == anime.ProviderId && optionProviderName == CurrentAnimeProviderName(anime) {
1175						// Extract total episodes from the label
1176						if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 {
1177							anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
1178							CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
1179							break
1180						}
1181					}
1182				}
1183			}
1184
1185			if anime.TotalEpisodes == 0 {
1186				CurdOut("Still unable to determine total episodes.")
1187				CurdOut(fmt.Sprintf("Your %s progress: %d", RemoteTrackingDisplayName(userCurdConfig), selectedAnilistAnime.Progress))
1188				episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, "Enter the episode you want to start from")
1189				if err != nil {
1190					Log("Invalid episode input: " + err.Error())
1191					ExitCurd(fmt.Errorf("Invalid episode number"))
1192				}
1193				anime.Ep.Number = episodeNumber
1194			} else {
1195				anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
1196			}
1197		} else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
1198			Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
1199			var answer string
1200			if userCurdConfig.RofiSelection {
1201				userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
1202				if err != nil {
1203					Log("Error getting user input: " + err.Error())
1204					ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1205				}
1206				answer = userInput
1207			} else {
1208				fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
1209				fmt.Scanln(&answer)
1210			}
1211			if isAffirmativeAnswer(answer) {
1212				anime.Ep.Number = 1
1213			} else {
1214				anime.Ep.Number = anime.TotalEpisodes
1215			}
1216		}
1217
1218		// If we reached here successfully, break the loop
1219		break
1220	}
1221}
1222
1223// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
1224func WriteTokenToFile(token string, filePath string) error {
1225	// Extract the directory path
1226	dir := filepath.Dir(filePath)
1227
1228	// Create all necessary parent directories
1229	if err := os.MkdirAll(dir, 0755); err != nil {
1230		return fmt.Errorf("failed to create directories: %v", err)
1231	}
1232
1233	// Write the token to the file, creating it if it doesn't exist
1234	err := os.WriteFile(filePath, []byte(token), 0644)
1235	if err != nil {
1236		return fmt.Errorf("failed to write token to file: %v", err)
1237	}
1238
1239	return nil
1240}
1241
1242func handleUnreleasedAnime(userCurdConfig *CurdConfig, user *User, anime *Anime, entry Entry) {
1243	title := entry.Media.Title.Romaji
1244	if userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" && entry.Media.Title.English != "" {
1245		title = entry.Media.Title.English
1246	}
1247	if title == "" {
1248		title = strconv.Itoa(entry.Media.ID)
1249	}
1250
1251	CurdOut(fmt.Sprintf("%s is not released yet.", title))
1252	options := []SelectionOption{}
1253	if UsesRemoteTracking(userCurdConfig) {
1254		options = append(options, SelectionOption{Key: "planning", Label: "Add to Plan to Watch"})
1255	}
1256	options = append(options,
1257		SelectionOption{Key: "details", Label: "Open AniList details"},
1258		SelectionOption{Key: "back", Label: "Back to list"},
1259	)
1260
1261	selected, err := promptSelect(options)
1262	if err != nil {
1263		Log(fmt.Sprintf("Error in unreleased anime prompt: %v", err))
1264		anime.Ep.ContinueLast = false
1265		return
1266	}
1267
1268	switch selected.Key {
1269	case "planning":
1270		if err := AddAnimeToList(entry.Media.ID, "PLANNING", user.Token); err != nil {
1271			Log(fmt.Sprintf("Error adding unreleased anime to planning: %v", err))
1272			CurdOut("Failed to add to Plan to Watch.")
1273		} else {
1274			CurdOut("Added to Plan to Watch.")
1275			if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
1276				Log("Error refreshing anime list: " + err.Error())
1277			}
1278		}
1279	case "details":
1280		url := fmt.Sprintf("https://anilist.co/anime/%d", entry.Media.ID)
1281		CurdOut(fmt.Sprintf("Opening %s", url))
1282		if err := browser.OpenURL(url); err != nil {
1283			Log(fmt.Sprintf("Error opening browser: %v", err))
1284			CurdOut("Failed to open browser.")
1285		}
1286	case "-1":
1287		ExitCurd(nil)
1288	}
1289	anime.Ep.ContinueLast = false
1290}
1291
1292func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1293	if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil {
1294		Log(fmt.Sprintf("Failed to resolve provider id: %v", err))
1295		CurdOut("Failed to resolve anime provider id: " + err.Error())
1296		exitWithRestore(1)
1297	}
1298
1299	// Validate inputs
1300	if anime.ProviderId == "" {
1301		CurdOut("Error: No anime ID found")
1302		exitWithRestore(1)
1303	}
1304	if anime.Ep.Number <= 0 {
1305		CurdOut("Error: Invalid episode number")
1306		exitWithRestore(1)
1307	}
1308
1309	if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1310		anime.Ep.Links = anime.Ep.NextEpisode.Links
1311		anime.Ep.StreamReferrer = ""
1312		anime.Ep.SubtitleURL = ""
1313		if anime.Ep.NextEpisode.ProviderName != "" {
1314			anime.ProviderName = anime.Ep.NextEpisode.ProviderName
1315			anime.ProviderId = anime.Ep.NextEpisode.ProviderId
1316		}
1317	} else {
1318		// Preferred-first resolve; diagnosed recovery only after that fails.
1319		episodeResult, ok := resolveEpisodeLinksWithRecovery(userCurdConfig, anime, nil, true)
1320		if !ok {
1321			RestoreScreen()
1322			return ""
1323		}
1324		Log(fmt.Sprintf("Successfully retrieved %s/%s episode link. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(episodeResult.Links)))
1325		anime.Ep.Links = episodeResult.Links
1326		applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1327	}
1328
1329	if len(anime.Ep.Links) == 0 {
1330		CurdOut("No episode links found")
1331		RestoreScreen()
1332		return ""
1333	}
1334	Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links)))
1335
1336	// Modify the goroutine in main.go where next episode links are fetched
1337	// Get next episode link in parallel
1338	go func() {
1339		nextEpNum := anime.Ep.Number + 1
1340		if nextEpNum <= anime.TotalEpisodes {
1341			// Get next canon episode number if filler skip is enabled
1342			if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) {
1343				nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum)
1344			}
1345			nextEpisode := *anime
1346			nextEpisode.ProviderId = anime.ProviderId
1347			nextEpisode.ProviderName = anime.ProviderName
1348			nextResult, err := ResolveEpisodeURL(*userCurdConfig, &nextEpisode, nextEpNum)
1349			if err != nil {
1350				Log(fmt.Sprintf("Error getting next episode link for ep %d: %v", nextEpNum, err))
1351			} else {
1352				anime.Ep.NextEpisode = NextEpisode{
1353					Number:       nextEpNum,
1354					Links:        nextResult.Links,
1355					ProviderName: nextResult.ProviderName,
1356					ProviderId:   nextResult.ProviderID,
1357					Mode:         nextResult.Mode,
1358				}
1359			}
1360		} else {
1361			Log(fmt.Sprintf("Next episode %d exceeds total episodes %d, skipping prefetch", nextEpNum, anime.TotalEpisodes))
1362		}
1363	}()
1364
1365	// Write anime.AnilistId to curd_id in the storage path
1366	idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1367	Log(fmt.Sprintf("idFilePath: %v", idFilePath))
1368	if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
1369		Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err))
1370	} else {
1371		if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
1372			Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err))
1373		}
1374	}
1375
1376	// Display starting message with cover image and episode info
1377	if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
1378		// Get the cached image path
1379		cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
1380		filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
1381		cachePath := filepath.Join(cacheDir, filename)
1382
1383		// Display the image if it exists in cache
1384		_, err := os.Stat(cachePath)
1385		if err == nil {
1386			// File exists
1387			Log(fmt.Sprintf("Image found at %s", cachePath))
1388			CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
1389		} else {
1390			// File does not exist
1391			Log(fmt.Sprintf("Image does not exist at %s", cachePath))
1392			CurdOut(fmt.Sprintf("%s - Episode %d",
1393				GetAnimeName(*anime),
1394				anime.Ep.Number))
1395
1396		}
1397	} else {
1398		CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
1399	}
1400	title := fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number)
1401	return StartVideoWithProviderFallback(userCurdConfig, anime, title)
1402}
1403
1404func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
1405	if anime == nil || anime.ProviderId == "" {
1406		return nil
1407	}
1408
1409	providerName, providerID := AnimeProviderID(anime)
1410	if providerName != "animepahe" || !ProviderEnabled("animepahe") {
1411		return nil
1412	}
1413	if !ProviderStackContains(userCurdConfig, "animepahe") {
1414		return nil
1415	}
1416
1417	provider, err := ProviderByName(providerName)
1418	if err != nil {
1419		return err
1420	}
1421
1422	query := GetAnimeName(*anime)
1423	if query == "" {
1424		query = anime.Title.Romaji
1425	}
1426	if query == "" {
1427		query = anime.Title.English
1428	}
1429
1430	resolved, err := resolveProviderID(provider, providerID, query)
1431	if err != nil {
1432		return err
1433	}
1434	if resolved != "" && resolved != providerID {
1435		Log(fmt.Sprintf("Resolved Animepahe provider id %s to runtime id %s", providerID, resolved))
1436		anime.ProviderId = resolved
1437		anime.ProviderName = providerName
1438	}
1439
1440	return nil
1441}
1442
1443func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason error) bool {
1444	providerName, _ := AnimeProviderID(anime)
1445	if providerName != "animepahe" || !ProviderEnabled("animepahe") {
1446		return false
1447	}
1448
1449	if reason != nil {
1450		Log(fmt.Sprintf("Attempting Animepahe provider reselect after error: %v", reason))
1451	}
1452
1453	query := GetAnimeName(*anime)
1454	if query == "" {
1455		query = anime.Title.Romaji
1456	}
1457	if query == "" {
1458		query = anime.Title.English
1459	}
1460	if query == "" {
1461		return false
1462	}
1463
1464	options, err := SearchAnime(query, userCurdConfig.SubOrDub)
1465	if err != nil {
1466		Log(fmt.Sprintf("Animepahe provider reselect search failed for %q: %v", query, err))
1467		return false
1468	}
1469	if len(options) == 0 {
1470		Log(fmt.Sprintf("Animepahe provider reselect found no results for %q", query))
1471		return false
1472	}
1473
1474	CurdOut("The saved Animepahe mapping is stale. Please select the anime again.")
1475	var trackerEntry *Entry
1476	if anime.TotalEpisodes > 0 {
1477		trackerEntry = &Entry{Media: Media{Episodes: anime.TotalEpisodes}}
1478	}
1479	selected, err := promptProviderSearchSelection(userCurdConfig, options, trackerEntry)
1480	if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" {
1481		if err != nil {
1482			Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err))
1483		}
1484		return false
1485	}
1486
1487	if selectedProviderName, rawProviderID, ok := ParseProviderQualifiedID(selected.Key); ok {
1488		anime.ProviderName = selectedProviderName
1489		anime.ProviderId = rawProviderID
1490	} else {
1491		anime.ProviderName = "animepahe"
1492		anime.ProviderId = selected.Key
1493	}
1494	anime.Ep.NextEpisode = NextEpisode{}
1495	Log(fmt.Sprintf("Updated Animepahe ProviderId to %s after stale mapping", anime.ProviderId))
1496	return true
1497}
1498
1499func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1500	// Create storage directory if it doesn't exist
1501	storagePath = os.ExpandEnv(storagePath)
1502	if err := os.MkdirAll(storagePath, 0755); err != nil {
1503		return fmt.Errorf("failed to create storage directory: %v", err)
1504	}
1505
1506	// Base URL for downloading config files
1507	baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
1508
1509	// Check each file
1510	for _, fileName := range filesToCheck {
1511		filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
1512
1513		// Skip if file already exists
1514		if _, err := os.Stat(filePath); err == nil {
1515			continue
1516		}
1517
1518		// Download file if it doesn't exist
1519		resp, err := sharedHTTPClient.Get(baseURL + fileName)
1520		if err != nil {
1521			return fmt.Errorf("failed to download %s: %v", fileName, err)
1522		}
1523		if resp.StatusCode != http.StatusOK {
1524			resp.Body.Close()
1525			return fmt.Errorf("failed to download %s: received status code %d", fileName, resp.StatusCode)
1526		}
1527
1528		// Create the file
1529		out, err := os.Create(filePath)
1530		if err != nil {
1531			resp.Body.Close()
1532			return fmt.Errorf("failed to create file %s: %v", fileName, err)
1533		}
1534
1535		// Write the content
1536		if _, err := io.Copy(out, resp.Body); err != nil {
1537			resp.Body.Close()
1538			out.Close()
1539			return fmt.Errorf("failed to write file %s: %v", fileName, err)
1540		}
1541		resp.Body.Close()
1542		if err := out.Close(); err != nil {
1543			return fmt.Errorf("failed to close file %s: %v", fileName, err)
1544		}
1545	}
1546
1547	return nil
1548}
1549
1550func getEntriesByCategory(list AnimeList, category string) []Entry {
1551	switch category {
1552	case "ALL":
1553		// Combine all categories into one slice. Dedupe by Media.ID so Show All
1554		// never surfaces the same anime twice (e.g. stale cache / dual-track edge cases).
1555		allEntries := make([]Entry, 0)
1556		allEntries = append(allEntries, list.Watching...)
1557		allEntries = append(allEntries, list.Completed...)
1558		allEntries = append(allEntries, list.Paused...)
1559		allEntries = append(allEntries, list.Dropped...)
1560		allEntries = append(allEntries, list.Planning...)
1561		allEntries = append(allEntries, list.Rewatching...)
1562		return dedupeEntriesByMediaID(allEntries)
1563	case "CURRENT":
1564		currentEntries := make([]Entry, 0, len(list.Watching)+len(list.Rewatching))
1565		currentEntries = append(currentEntries, list.Watching...)
1566		currentEntries = append(currentEntries, list.Rewatching...)
1567		return dedupeEntriesByMediaID(currentEntries)
1568	case "COMPLETED":
1569		return dedupeEntriesByMediaID(list.Completed)
1570	case "PAUSED":
1571		return dedupeEntriesByMediaID(list.Paused)
1572	case "DROPPED":
1573		return dedupeEntriesByMediaID(list.Dropped)
1574	case "PLANNING":
1575		return dedupeEntriesByMediaID(list.Planning)
1576	case "REWATCHING": // Added for completeness, though "ALL" covers it.
1577		return dedupeEntriesByMediaID(list.Rewatching)
1578	default:
1579		return []Entry{}
1580	}
1581}
1582
1583func NextEpisodePromptCLI(userCurdConfig *CurdConfig) bool {
1584	anime := GetGlobalAnime()
1585
1586	// Show the next episode number that will be started
1587	nextEpisodeNum := anime.Ep.Number + 1
1588	isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1589	if isLastKnownEpisode {
1590		CurdOut("Finish this series?")
1591	} else {
1592		CurdOut(fmt.Sprintf("Start next episode (%d)?", nextEpisodeNum))
1593	}
1594
1595	// Create options for the selection - no "quit" option since it's built into selection menu
1596	label := fmt.Sprintf("Yes, continue to episode %d", nextEpisodeNum)
1597	if isLastKnownEpisode {
1598		label = "Yes, finish series"
1599	}
1600	options := []SelectionOption{
1601		{Key: "yes", Label: label},
1602	}
1603
1604	// Use DynamicSelect for CLI mode
1605	selectedOption, err := DynamicSelect(options)
1606	if err != nil {
1607		Log(fmt.Sprintf("Error in CLI next episode prompt selection: %v", err))
1608		return false
1609	}
1610
1611	Log(fmt.Sprintf("CLI User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1612
1613	if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1614		// User selected to quit/back via the built-in option
1615		CurdOut("Exiting")
1616		return false
1617	}
1618
1619	return selectedOption.Key == "yes"
1620}
1621
1622// NextEpisodePromptContinuous provides a continuous next episode prompt for CLI mode
1623// This runs throughout the episode duration and handles completion logic
1624func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1625	anime := GetGlobalAnime()
1626
1627	for {
1628		// Check if episode has started
1629		if !anime.Ep.Started {
1630			time.Sleep(1 * time.Second)
1631			continue
1632		}
1633
1634		// Show the next episode number that will be started
1635		nextEpisodeNum := anime.Ep.Number + 1
1636		isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1637		if isLastKnownEpisode {
1638			CurdOut("Finish this series or quit?")
1639		} else {
1640			CurdOut(fmt.Sprintf("Continue to next episode (%d) or quit?", nextEpisodeNum))
1641		}
1642
1643		// Create options for the selection - no "quit" option since it's built into selection menu
1644		label := "Yes, start next episode now"
1645		if isLastKnownEpisode {
1646			label = "Yes, finish series"
1647		}
1648		options := []SelectionOption{
1649			{Key: "yes", Label: label},
1650		}
1651
1652		// Use DynamicSelect for CLI mode
1653		selectedOption, err := DynamicSelect(options)
1654		if err != nil {
1655			Log(fmt.Sprintf("Error in CLI continuous next episode prompt: %v", err))
1656			break
1657		}
1658
1659		Log(fmt.Sprintf("CLI Continuous User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1660
1661		if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1662			// User selected to quit/back via the built-in option
1663
1664			// Check completion percentage
1665			percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
1666
1667			if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
1668				// Episode is considered completed, mark it and update progress
1669				anime.Ep.IsCompleted = true
1670
1671				// Handle completion if this was the last episode
1672				if anime.Ep.Number == anime.TotalEpisodes {
1673					HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
1674				}
1675
1676				// Update local database
1677				if updateErr := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime), CurrentAnimeProviderName(anime)); updateErr != nil {
1678					Log("Error updating local database on quit: " + updateErr.Error())
1679				}
1680
1681				if !(anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && anime.Rewatching) {
1682					completedEpisode := anime.Ep.Number
1683					go func(progressEpisode int) {
1684						if progressErr := UpdateAnimeProgress(userToken, anime.AnilistId, progressEpisode); progressErr != nil {
1685							Log("Error updating Anilist progress on quit: " + progressErr.Error())
1686						}
1687					}(completedEpisode)
1688				}
1689
1690				CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched))
1691			} else {
1692				CurdOut(fmt.Sprintf("Episode not completed (%.1f%% watched). Exiting.", percentageWatched))
1693			}
1694
1695			ExitMPV(anime.Ep.Player.SocketPath)
1696			ExitCurd(nil)
1697			return
1698		}
1699
1700		if selectedOption.Key == "yes" {
1701			// User wants to start next episode immediately
1702			anime.Ep.IsCompleted = true
1703			socketPath := anime.Ep.Player.SocketPath
1704			if anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes {
1705				ExitMPV(socketPath)
1706			}
1707			StartNextEpisode(anime, userCurdConfig, databaseFile, userToken)
1708			ExitMPV(socketPath)
1709			return // Exit this function, let the main loop handle next episode
1710		}
1711	}
1712}
1713
1714// Simple next episode prompt for Rofi mode - just asks if user wants to continue
1715func NextEpisodePromptRofi(userCurdConfig *CurdConfig) bool {
1716	anime := GetGlobalAnime()
1717
1718	// Show the next episode number that will be started
1719	nextEpisodeNum := anime.Ep.Number + 1
1720	isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1721
1722	// Create options for the selection
1723	label := fmt.Sprintf("Yes, start episode %d", nextEpisodeNum)
1724	if isLastKnownEpisode {
1725		label = "Yes, finish series"
1726	}
1727	options := []SelectionOption{
1728		{Key: "yes", Label: label},
1729	}
1730
1731	// Use DynamicSelect for Rofi mode
1732	selectedOption, err := DynamicSelect(options)
1733	if err != nil {
1734		Log(fmt.Sprintf("Error in next episode prompt selection: %v", err))
1735		return false
1736	}
1737
1738	Log(fmt.Sprintf("Rofi User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1739
1740	return selectedOption.Key == "yes"
1741}
1742
1743// StartNextEpisode handles the logic for starting the next episode
1744// It updates the episode number, resets necessary flags, and handles database updates
1745func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1746	// Save previous episode number for progress update
1747	prevEpisode := anime.Ep.Number
1748
1749	// Check if we just completed the last episode
1750	if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1751		// Handle scoring and completion for the last episode
1752		HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
1753
1754		if !anime.Rewatching {
1755			err := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1756			if err != nil {
1757				Log("Error updating Anilist progress: " + err.Error())
1758			}
1759		}
1760		// Note: UpdateAnimeProgress already outputs a message on success
1761
1762		CurdOut("Series completed!")
1763		ExitCurd(nil)
1764		return
1765	}
1766
1767	// Increment episode number
1768	anime.Ep.Number++
1769
1770	// Check if we've reached the end of the series
1771	if anime.TotalEpisodes > 0 && anime.Ep.Number > anime.TotalEpisodes {
1772		CurdOut("Reached end of series")
1773		ExitCurd(nil)
1774		return
1775	}
1776
1777	// Use prefetched links if available for the next episode
1778	if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1779		anime.Ep.Links = anime.Ep.NextEpisode.Links
1780		anime.Ep.StreamReferrer = ""
1781		anime.Ep.SubtitleURL = ""
1782		if anime.Ep.NextEpisode.ProviderName != "" {
1783			anime.ProviderName = anime.Ep.NextEpisode.ProviderName
1784			anime.ProviderId = anime.Ep.NextEpisode.ProviderId
1785		}
1786		Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number))
1787	} else {
1788		// Clear links to force fetching new ones
1789		anime.Ep.Links = []string{}
1790		Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
1791	}
1792
1793	// Reset episode flags
1794	anime.Ep.Started = false
1795	anime.Ep.IsCompleted = false
1796
1797	// Log the transition
1798	Log("Completed episode, starting next.")
1799
1800	// Update local database
1801	err := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, GetAnimeName(*anime), CurrentAnimeProviderName(anime))
1802	if err != nil {
1803		Log("Error updating local database: " + err.Error())
1804	}
1805
1806	go func() {
1807		if progressErr := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode); progressErr != nil {
1808			Log("Error updating Anilist progress: " + progressErr.Error())
1809		}
1810	}()
1811
1812	// Output message to user
1813	CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
1814}
1815
1816// HandleLastEpisodeCompletion handles scoring and completion for the last episode
1817func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
1818	if anime.TotalEpisodes <= 0 || anime.Ep.Number != anime.TotalEpisodes {
1819		return
1820	}
1821
1822	summary := []string{}
1823	canWriteRemote := ShouldWriteRemoteTracking(userCurdConfig, anime)
1824
1825	if userCurdConfig.ScoreOnCompletion && !anime.IsAiring && canWriteRemote {
1826		CurdOut("You've completed this anime! Would you like to rate it?")
1827
1828		scoreOptions := []SelectionOption{
1829			{Key: "yes", Label: "Yes, rate this anime"},
1830			{Key: "no", Label: "No, skip rating"},
1831		}
1832
1833		selectedOption, err := DynamicSelect(scoreOptions)
1834		if err != nil {
1835			Log(fmt.Sprintf("Error in score prompt selection: %v", err))
1836		} else if selectedOption.Key == "yes" {
1837			err = RateAnime(userToken, anime.AnilistId)
1838			if err != nil {
1839				Log(fmt.Sprintf("Error rating anime: %v", err))
1840				CurdOut("Failed to rate anime")
1841				summary = append(summary, "rating failed")
1842			} else {
1843				CurdOut("Anime rated successfully!")
1844				summary = append(summary, "rating saved")
1845			}
1846		} else {
1847			summary = append(summary, "rating skipped")
1848		}
1849		// Back (-2) and no are treated as skip
1850	} else {
1851		summary = append(summary, "rating skipped")
1852	}
1853
1854	if !anime.IsAiring && canWriteRemote {
1855		if anime.Rewatching {
1856			err := CompleteAnimeRewatch(userToken, *anime)
1857			if err != nil {
1858				Log("Error completing anime rewatch: " + err.Error())
1859				summary = append(summary, "rewatch completion failed")
1860			} else {
1861				summary = append(summary, "rewatch completed")
1862			}
1863		} else {
1864			err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED")
1865			if err != nil {
1866				Log("Error updating anime status to completed: " + err.Error())
1867				summary = append(summary, "status update failed")
1868			} else {
1869				summary = append(summary, "marked completed")
1870			}
1871		}
1872	} else if !anime.IsAiring {
1873		summary = append(summary, "tracker updates skipped")
1874	}
1875
1876	if sequelSummary := handleSequelCheck(userCurdConfig, anime, userToken); sequelSummary != "" {
1877		summary = append(summary, sequelSummary)
1878	}
1879	if len(summary) > 0 {
1880		CurdOut("Completion summary: " + strings.Join(summary, "; "))
1881	}
1882}
1883
1884// handleSequelCheck checks for sequels and prompts the user accordingly
1885func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken string) (summary string) {
1886	if !ShouldWriteRemoteTracking(userCurdConfig, anime) {
1887		return "sequel check skipped"
1888	}
1889
1890	// Recover from any panics in this function to prevent crashes
1891	defer func() {
1892		if r := recover(); r != nil {
1893			Log(fmt.Sprintf("Recovered from panic in handleSequelCheck: %v", r))
1894			summary = "sequel check failed"
1895		}
1896	}()
1897
1898	// Fetch sequel information
1899	sequels, err := GetAnimeSequel(anime.AnilistId, userToken)
1900	if err != nil {
1901		Log(fmt.Sprintf("Error fetching sequel information: %v", err))
1902		return "sequel check failed"
1903	}
1904
1905	if len(sequels) == 0 {
1906		Log("No sequel found for this anime")
1907		return "no sequel found"
1908	}
1909
1910	sequel := &sequels[0]
1911	if len(sequels) > 1 {
1912		selectedSequel, ok := selectSequel(userCurdConfig, sequels)
1913		if !ok {
1914			return "sequel skipped"
1915		}
1916		sequel = selectedSequel
1917	}
1918
1919	return promptSequelAction(userCurdConfig, sequel, userToken)
1920}
1921
1922func selectSequel(userCurdConfig *CurdConfig, sequels []SequelInfo) (*SequelInfo, bool) {
1923	CurdOut("Multiple sequels found.")
1924	options := make([]SelectionOption, 0, len(sequels)+1)
1925	for i := range sequels {
1926		title := sequelDisplayTitle(userCurdConfig, &sequels[i])
1927		status := strings.ToLower(strings.ReplaceAll(sequels[i].Status, "_", " "))
1928		options = append(options, SelectionOption{
1929			Key:   strconv.Itoa(i),
1930			Label: fmt.Sprintf("%s (%s)", title, status),
1931		})
1932	}
1933	options = append(options, SelectionOption{Key: "skip", Label: "Skip"})
1934
1935	selected, err := promptSelect(options)
1936	if err != nil {
1937		Log(fmt.Sprintf("Error selecting sequel: %v", err))
1938		return nil, false
1939	}
1940	if selected.Key == "skip" || selected.Key == "-1" || selected.Key == "-2" {
1941		return nil, false
1942	}
1943	index, err := strconv.Atoi(selected.Key)
1944	if err != nil || index < 0 || index >= len(sequels) {
1945		return nil, false
1946	}
1947	return &sequels[index], true
1948}
1949
1950func sequelDisplayTitle(userCurdConfig *CurdConfig, sequel *SequelInfo) string {
1951	if sequel == nil {
1952		return ""
1953	}
1954	if userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" && sequel.Title.English != "" {
1955		return sequel.Title.English
1956	}
1957	if sequel.Title.Romaji != "" {
1958		return sequel.Title.Romaji
1959	}
1960	return strconv.Itoa(sequel.ID)
1961}
1962
1963func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToken string) string {
1964	if sequel == nil {
1965		return ""
1966	}
1967
1968	sequelTitle := sequelDisplayTitle(userCurdConfig, sequel)
1969	Log(fmt.Sprintf("Found sequel: %s (ID: %d)", sequelTitle, sequel.ID))
1970
1971	currentUser := GetGlobalUser()
1972	userAnimeList := AnimeList{}
1973	if currentUser != nil {
1974		userAnimeList = currentUser.AnimeList
1975	}
1976	sequelStatus, isInList := "", false
1977	if hasAnyEntries(userAnimeList) {
1978		sequelStatus, isInList = FindSequelInAnimeList(userAnimeList, sequel.ID)
1979	}
1980
1981	if isInList {
1982		CurdOut(fmt.Sprintf("Sequel found: %s (%s)", sequelTitle, sequelStatus))
1983	} else {
1984		CurdOut(fmt.Sprintf("Sequel found: %s", sequelTitle))
1985	}
1986
1987	options := []SelectionOption{}
1988	if sequel.Status != "NOT_YET_RELEASED" {
1989		if !isInList || sequelStatus == "PLANNING" || sequelStatus == "PAUSED" || sequelStatus == "DROPPED" {
1990			options = append(options, SelectionOption{Key: "watching", Label: "Add to Watching"})
1991		}
1992	}
1993	if !isInList || sequelStatus != "PLANNING" {
1994		options = append(options, SelectionOption{Key: "planning", Label: "Add to Plan to Watch"})
1995	}
1996	options = append(options,
1997		SelectionOption{Key: "details", Label: "Open AniList details"},
1998		SelectionOption{Key: "skip", Label: "Skip"},
1999	)
2000
2001	selected, err := promptSelect(options)
2002	if err != nil {
2003		Log(fmt.Sprintf("Error in sequel action prompt: %v", err))
2004		return "sequel action failed"
2005	}
2006
2007	switch selected.Key {
2008	case "watching":
2009		if err := AddAnimeToList(sequel.ID, "CURRENT", userToken); err != nil {
2010			Log(fmt.Sprintf("Error adding sequel to watching list: %v", err))
2011			CurdOut("Failed to add sequel to Watching.")
2012			return "sequel add failed"
2013		} else {
2014			CurdOut(fmt.Sprintf("Added '%s' to Watching.", sequelTitle))
2015			return "sequel added to Watching"
2016		}
2017	case "planning":
2018		if err := AddAnimeToList(sequel.ID, "PLANNING", userToken); err != nil {
2019			Log(fmt.Sprintf("Error adding sequel to planning list: %v", err))
2020			CurdOut("Failed to add sequel to Plan to Watch.")
2021			return "sequel add failed"
2022		} else {
2023			CurdOut(fmt.Sprintf("Added '%s' to Plan to Watch.", sequelTitle))
2024			return "sequel added to Plan to Watch"
2025		}
2026	case "details":
2027		url := sequel.SiteURL
2028		if url == "" {
2029			url = fmt.Sprintf("https://anilist.co/anime/%d", sequel.ID)
2030		}
2031		CurdOut(fmt.Sprintf("Opening %s", url))
2032		if err := browser.OpenURL(url); err != nil {
2033			Log(fmt.Sprintf("Error opening browser: %v", err))
2034			CurdOut("Failed to open browser.")
2035			return "sequel details failed"
2036		}
2037		return "sequel details opened"
2038	case "skip", "-1", "-2":
2039		Log("User skipped sequel action")
2040	}
2041	return "sequel skipped"
2042}
2043
2044// ChangeProvider allows the user to switch the anime provider
2045func ChangeProvider(userCurdConfig *CurdConfig) {
2046	options := providerSelectionOptions()
2047	if len(options) == 0 {
2048		CurdOut("\nNo providers are currently enabled.\n")
2049		return
2050	}
2051
2052	selected, err := DynamicSelect(options)
2053	if err != nil || selected.Key == "-1" || selected.Key == "-2" {
2054		return
2055	}
2056
2057	// Update the config
2058	providerValue := canonicalProviderConfigValue(selected.Key)
2059	userCurdConfig.Provider = providerValue
2060	CurrentProvider = nil // reset the provider instance
2061
2062	// Save to config file
2063	configPath := GlobalConfigPath
2064	configMap, err := LoadConfigFromFile(configPath)
2065	if err == nil {
2066		configMap["Provider"] = providerValue
2067		SaveConfigToFile(configPath, configMap)
2068	}
2069
2070	CurdOut(fmt.Sprintf("\nProvider successfully changed to %s.\n", providerConfigDisplayLabel(userCurdConfig.Provider)))
2071	time.Sleep(1 * time.Second)
2072}