internal/curd.go

2153 lines · 70398 bytes

   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			os.Exit(1)
 161		} else {
 162			os.Exit(1)
 163		}
 164	}
 165	os.Exit(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
 434	// Determine the correct binary name based on OS and architecture
 435	var binaryName string
 436	switch runtime.GOOS {
 437	case "windows":
 438		if runtime.GOARCH == "arm64" {
 439			binaryName = "curd-windows-arm64.exe"
 440		} else {
 441			binaryName = "curd-windows-x86_64.exe"
 442		}
 443	case "darwin": // macOS
 444		switch runtime.GOARCH {
 445		case "amd64":
 446			binaryName = "curd-macos-x86_64"
 447		case "arm64":
 448			binaryName = "curd-macos-arm64"
 449		default:
 450			binaryName = "curd-macos-universal"
 451		}
 452	case "linux":
 453		switch runtime.GOARCH {
 454		case "amd64":
 455			binaryName = "curd-linux-x86_64"
 456		case "arm64":
 457			binaryName = "curd-linux-arm64"
 458		default:
 459			return fmt.Errorf("unsupported Linux architecture: %s", runtime.GOARCH)
 460		}
 461	default:
 462		return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
 463	}
 464
 465	// GitHub release URL for curd
 466	url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName)
 467
 468	// Temporary path for the downloaded curd executable
 469	tmpPath := executablePath + ".tmp"
 470
 471	// Download the curd executable
 472	resp, err := sharedHTTPClient.Get(url)
 473	if err != nil {
 474		return fmt.Errorf("failed to download file: %v", err)
 475	}
 476	defer resp.Body.Close()
 477
 478	// Check if the download was successful
 479	if resp.StatusCode != http.StatusOK {
 480		return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
 481	}
 482
 483	// Create a new temporary file
 484	out, err := os.Create(tmpPath)
 485	if err != nil {
 486		return fmt.Errorf("failed to create temporary file: %v", err)
 487	}
 488	defer out.Close()
 489
 490	// Set file permissions
 491	if err := out.Chmod(0755); err != nil {
 492		return fmt.Errorf("failed to set file permissions: %v", err)
 493	}
 494
 495	// Copy the downloaded content to the temporary file
 496	if _, err := io.Copy(out, resp.Body); err != nil {
 497		return fmt.Errorf("failed to write to temporary file: %v", err)
 498	}
 499
 500	// Close the file before renaming
 501	out.Close()
 502
 503	// Replace the old executable with the new one
 504	if runtime.GOOS == "windows" {
 505		// On Windows, we need to rename the old file first
 506		oldPath := executablePath + ".old"
 507		err = os.Rename(executablePath, oldPath)
 508		if err != nil {
 509			return fmt.Errorf("failed to rename old executable: %v", err)
 510		}
 511		err = os.Rename(tmpPath, executablePath)
 512		if err != nil {
 513			// Try to restore the old executable if the rename fails
 514			os.Rename(oldPath, executablePath)
 515			return fmt.Errorf("failed to rename new executable: %v", err)
 516		}
 517		os.Remove(oldPath)
 518	} else {
 519		// On Unix systems, we can directly rename
 520		if err := os.Rename(tmpPath, executablePath); err != nil {
 521			return fmt.Errorf("failed to replace executable: %v", err)
 522		}
 523	}
 524
 525	return nil
 526}
 527
 528func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
 529	var query string
 530	// Remove the redeclared variable declaration since animeOptions is already declared above
 531	var animeMapPreview map[string]RofiSelectPreview
 532	var animeOptions []SelectionOption
 533	var err error
 534	var anilistSelectedOption SelectionOption
 535
 536	query, err = promptText(userCurdConfig, "Enter the anime name", false)
 537	if err != nil {
 538		Log("Error getting user input: " + err.Error())
 539		ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
 540	}
 541	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 542		animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
 543	} else {
 544		animeOptions, err = SearchAnimeAnilist(query, user.Token)
 545		if err != nil {
 546			Log(fmt.Sprintf("Failed to search anime: %v", err))
 547			ExitCurd(fmt.Errorf("Failed to search anime"))
 548		}
 549	}
 550	if err != nil {
 551		Log(fmt.Sprintf("Failed to search anime: %v", err))
 552		ExitCurd(fmt.Errorf("Failed to search anime"))
 553	}
 554	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 555		anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
 556	} else {
 557		anilistSelectedOption, err = DynamicSelect(animeOptions)
 558	}
 559	if err != nil {
 560		Log(fmt.Sprintf("No anime available: %v", err))
 561		ExitCurd(fmt.Errorf("No anime available"))
 562	}
 563
 564	if anilistSelectedOption.Key == "-1" {
 565		ExitCurd(nil)
 566	}
 567
 568	// Handle back button - return to caller
 569	if anilistSelectedOption.Key == "-2" {
 570		return SelectionOption{Key: "-2", Label: "Back"}
 571	}
 572
 573	animeID, err := strconv.Atoi(anilistSelectedOption.Key)
 574	if err != nil {
 575		Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err))
 576		ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
 577	}
 578
 579	if !UsesRemoteTracking(userCurdConfig) {
 580		return anilistSelectedOption
 581	}
 582
 583	// Add category selection before adding to list
 584	categories := []SelectionOption{
 585		{Key: "CURRENT", Label: "Currently Watching"},
 586		{Key: "COMPLETED", Label: "Completed"},
 587		{Key: "PAUSED", Label: "On Hold"},
 588		{Key: "DROPPED", Label: "Dropped"},
 589		{Key: "PLANNING", Label: "Plan to Watch"},
 590		{Key: "REPEATING", Label: "Rewatching"}, // Anilist uses REPEATING for rewatching
 591	}
 592
 593	ClearScreen()
 594	CurdOut("Select which list to add the anime to:")
 595
 596	categorySelection, err := DynamicSelect(categories)
 597	if err != nil {
 598		Log(fmt.Sprintf("Failed to select category: %v", err))
 599		ExitCurd(fmt.Errorf("Failed to select category"))
 600	}
 601
 602	if categorySelection.Key == "-1" {
 603		ExitCurd(nil)
 604	}
 605
 606	// Handle back button - return to caller
 607	if categorySelection.Key == "-2" {
 608		return SelectionOption{Key: "-2", Label: "Back"}
 609	}
 610
 611	err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
 612	if err != nil {
 613		Log(fmt.Sprintf("Failed to add anime to list: %v", err))
 614		ExitCurd(fmt.Errorf("Failed to add anime to list"))
 615	}
 616
 617	if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
 618		Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
 619		ExitCurd(fmt.Errorf("Failed to refresh anime list"))
 620	}
 621
 622	return anilistSelectedOption
 623}
 624
 625func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) {
 626	var err error
 627	var startingRewatch bool
 628
 629	// Filter anime list based on selected category
 630	var animeListOptions []SelectionOption
 631	var animeListMapPreview map[string]RofiSelectPreview
 632
 633	// Initialize anime list. On a cache hit this is instant (reads from disk) and
 634	// the user ID is seeded from the cached payload, avoiding a blocking network
 635	// round-trip to AniList. The real user ID + latest list are refreshed in the
 636	// background goroutine inside InitializeUserAnimeList.
 637	if err := InitializeUserAnimeList(userCurdConfig, user); err != nil {
 638		Log(fmt.Sprintf("Failed to initialize anime list: %v", err))
 639		ExitCurd(fmt.Errorf("Failed to get user data\nYou can reset the token by running `curd -change-token`"))
 640	}
 641
 642	// Variables for selection results (used in both branches and after)
 643	var anilistSelectedOption SelectionOption
 644	var selectedAllanimeAnime SelectionOption
 645	var userQuery string
 646	_ = selectedAllanimeAnime // Used later in the function
 647
 648	// Navigation loop for the entire setup process
 649	for {
 650		startingRewatch = false
 651
 652		// If continueLast flag is set, directly get the last watched anime
 653		if anime.Ep.ContinueLast {
 654			// Get the last anime ID from the curd_id file
 655			idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
 656			idBytes, err := os.ReadFile(idFilePath)
 657			if err != nil {
 658				Log("Error reading curd_id file: " + err.Error())
 659				ExitCurd(fmt.Errorf("No last watched anime found"))
 660			}
 661
 662			anilistID, err := strconv.Atoi(string(idBytes))
 663			if err != nil {
 664				Log("Error converting anilist ID: " + err.Error())
 665				ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
 666			}
 667
 668			// Find the anime in database
 669			animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
 670			if animePointer == nil {
 671				ExitCurd(fmt.Errorf("Last watched anime not found in database"))
 672			}
 673
 674			// Set the anime details
 675			anime.AnilistId = animePointer.AnilistId
 676			anilistSelectedOption.Key = strconv.Itoa(animePointer.AnilistId)
 677			// anime.ProviderId = animePointer.ProviderId
 678			// anime.Title = animePointer.Title
 679			// anime.Ep.Number = animePointer.Ep.Number
 680			// anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
 681			// anime.Ep.Resume = true
 682
 683		} else {
 684			// Navigation loop for category and anime selection
 685		categorySelectionLoop:
 686			for {
 687				// Skip category selection if Current flag is set
 688				var categorySelection SelectionOption
 689				if userCurdConfig.CurrentCategory {
 690					categorySelection = SelectionOption{
 691						Key:   "CURRENT",
 692						Label: "Currently Watching",
 693					}
 694				} else {
 695					// Create category selection map
 696					// Get ordered categories
 697					orderedCategories := getOrderedCategories(userCurdConfig)
 698
 699					// Use DynamicSelect with ordered categories directly
 700					categorySelection, err = DynamicSelect(orderedCategories)
 701
 702					if err != nil {
 703						Log(fmt.Sprintf("Failed to select category: %v", err))
 704						ExitCurd(fmt.Errorf("Failed to select category"))
 705					}
 706
 707					if categorySelection.Key == "-1" {
 708						ExitCurd(nil)
 709					}
 710
 711					if categorySelection.Key == "-2" {
 712						continue
 713					}
 714
 715					// Handle options
 716					if categorySelection.Key == "PROVIDER" {
 717						ClearScreen()
 718						ChangeProvider(userCurdConfig)
 719						ClearScreen()
 720						continue categorySelectionLoop
 721					} else if categorySelection.Key == "TRACKER" {
 722						ClearScreen()
 723						ChangeTracker(userCurdConfig, user)
 724						ClearScreen()
 725						continue categorySelectionLoop
 726					} else if categorySelection.Key == "UPDATE" {
 727						ClearScreen()
 728						UpdateAnimeEntry(userCurdConfig, user)
 729						// If UpdateAnimeEntry returns, user pressed back - continue to category selection
 730						ClearScreen()
 731						continue categorySelectionLoop
 732					} else if categorySelection.Key == "UNTRACKED" {
 733						ClearScreen()
 734						WatchUntracked(userCurdConfig)
 735						// If WatchUntracked returns, user pressed back OR watched is done- continue to category selection
 736						ClearScreen()
 737						continue categorySelectionLoop
 738					} else if categorySelection.Key == "REMAP_PROVIDER" {
 739						ClearScreen()
 740						RemapProviderAnime(userCurdConfig, user, databaseAnimes)
 741						ClearScreen()
 742						continue categorySelectionLoop
 743					} else if categorySelection.Key == "CONTINUE_LAST" {
 744						anime.Ep.ContinueLast = true
 745					}
 746
 747					ClearScreen()
 748				}
 749
 750				if user.ListSync != nil {
 751					user.AnimeList = user.ListSync.Current()
 752				}
 753
 754				if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 755					animeListMapPreview = buildCategoryPreviewOptions(user.AnimeList, categorySelection.Key)
 756				} else {
 757					animeListOptions = buildCategorySelectionOptions(user.AnimeList, categorySelection.Key)
 758				}
 759
 760				// Anime selection loop (for back navigation)
 761			animeSelectionLoop:
 762				for {
 763					if anime.Ep.ContinueLast {
 764						// Get the last watched anime ID from the curd_id file
 765						curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
 766						curdIDBytes, err := os.ReadFile(curdIDPath)
 767						if err != nil {
 768							Log(fmt.Sprintf("Error reading curd_id file: %v", err))
 769							ExitCurd(fmt.Errorf("Error reading curd_id file"))
 770						}
 771
 772						lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
 773						if err != nil {
 774							Log(fmt.Sprintf("Error converting curd_id to integer: %v", err))
 775							ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
 776						}
 777
 778						anime.AnilistId = lastWatchedID
 779						anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
 780						break categorySelectionLoop
 781					}
 782
 783					// Select anime to watch (Anilist)
 784					var err error
 785					if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 786						anilistSelectedOption, err = DynamicSelectPreviewWithRefresh(animeListMapPreview, true, &PreviewSelectionRefreshConfig{
 787							Updates: user.ListSync.Updates(),
 788							BuildOptions: func(list AnimeList) map[string]RofiSelectPreview {
 789								return buildCategoryPreviewOptions(list, categorySelection.Key)
 790							},
 791						})
 792					} else {
 793						// Add "Add new anime" option to the slice
 794						tempOptions := make([]SelectionOption, len(animeListOptions))
 795						copy(tempOptions, animeListOptions)
 796
 797						tempOptions = append(tempOptions, SelectionOption{
 798							Key:   "add_new",
 799							Label: "Add new anime",
 800						})
 801
 802						anilistSelectedOption, err = DynamicSelectWithRefresh(tempOptions, &SelectionRefreshConfig{
 803							Updates: user.ListSync.Updates(),
 804							BuildOptions: func(list AnimeList) []SelectionOption {
 805								updatedOptions := buildCategorySelectionOptions(list, categorySelection.Key)
 806
 807								updatedOptions = append(updatedOptions, SelectionOption{
 808									Key:   "add_new",
 809									Label: "Add new anime",
 810								})
 811								return updatedOptions
 812							},
 813						})
 814					}
 815					if err != nil {
 816						Log(fmt.Sprintf("Error selecting anime: %v", err))
 817						ExitCurd(fmt.Errorf("Error selecting anime"))
 818					}
 819
 820					Log(anilistSelectedOption)
 821
 822					if anilistSelectedOption.Key == "-1" {
 823						ExitCurd(nil)
 824					}
 825
 826					// Handle back navigation - go back to category selection
 827					if anilistSelectedOption.Key == "-2" {
 828						if userCurdConfig.CurrentCategory {
 829							// If CurrentCategory is forced, back means quit
 830							ExitCurd(nil)
 831						}
 832						ClearScreen()
 833						continue categorySelectionLoop
 834					}
 835
 836					if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
 837						addResult := AddNewAnime(userCurdConfig, anime, user, databaseAnimes)
 838						if addResult.Key == "-2" {
 839							// Back from add new anime goes to anime selection
 840							ClearScreen()
 841							continue animeSelectionLoop
 842						}
 843						anilistSelectedOption = addResult
 844					}
 845
 846					anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
 847					if err != nil {
 848						Log(fmt.Sprintf("Error converting Anilist ID: %v", err))
 849						ExitCurd(fmt.Errorf("Error converting Anilist ID"))
 850					}
 851
 852					// Successfully selected anime, break out of both loops
 853					break categorySelectionLoop
 854				}
 855			}
 856		}
 857		// Wait for the background refresh goroutine to finish before reading
 858		// progress+1. RefreshDone() is a channel that is closed (broadcast) the
 859		// instant the goroutine completes — no polling, no race with the UI
 860		// Updates consumer that already drained the updates channel.
 861		if user.ListSync != nil {
 862			select {
 863			case <-user.ListSync.RefreshDone():
 864				Log("Background refresh done, using latest anime list for playback")
 865			case <-time.After(10 * time.Second):
 866				Log("Timed out waiting for background anime list refresh; using cached list")
 867			}
 868			user.AnimeList = user.ListSync.Current()
 869		}
 870
 871		animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
 872
 873		// Get anime entry
 874		selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
 875		if err != nil {
 876			if UsesRemoteTracking(userCurdConfig) {
 877				Log(fmt.Sprintf("Can not find the anime in tracked anime list: %v", err))
 878				ExitCurd(fmt.Errorf("Can not find the anime in tracked anime list"))
 879			}
 880
 881			fallbackAnime, fallbackErr := GetAnimeDataByID(anime.AnilistId, "")
 882			if fallbackErr != nil {
 883				Log(fmt.Sprintf("Failed to fetch fallback anime data: %v", fallbackErr))
 884				ExitCurd(fmt.Errorf("Failed to get anime data"))
 885			}
 886
 887			selectedAnilistAnime = &Entry{
 888				Media: Media{
 889					ID:       fallbackAnime.AnilistId,
 890					MalID:    fallbackAnime.MalId,
 891					Episodes: fallbackAnime.TotalEpisodes,
 892					Title:    fallbackAnime.Title,
 893					Status:   "FINISHED",
 894				},
 895				Progress:   0,
 896				Status:     "CURRENT",
 897				CoverImage: fallbackAnime.CoverImage,
 898			}
 899		}
 900
 901		if selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED" {
 902			handleUnreleasedAnime(userCurdConfig, user, anime, *selectedAnilistAnime)
 903			ClearScreen()
 904			continue
 905		}
 906
 907		// Set anime entry
 908		anime.Title = selectedAnilistAnime.Media.Title
 909		anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
 910		anime.CoverImage = selectedAnilistAnime.CoverImage
 911		if selectedAnilistAnime.Media.MalID != 0 {
 912			anime.MalId = selectedAnilistAnime.Media.MalID
 913		}
 914		if anime.MalId == 0 {
 915			anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
 916		}
 917		anime.IsAiring = selectedAnilistAnime.Media.Status == "RELEASING" || selectedAnilistAnime.Media.Status == "NOT_YET_RELEASED"
 918		anime.Rewatching = selectedAnilistAnime.Status == "REPEATING"
 919		anime.Repeat = selectedAnilistAnime.Repeat
 920		anime.StartedAt = selectedAnilistAnime.StartedAt
 921		anime.CompletedAt = selectedAnilistAnime.CompletedAt
 922		anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
 923		userQuery = anime.Title.Romaji
 924
 925		if selectedAnilistAnime.Status == "COMPLETED" {
 926			CurdOut("This anime is completed. Start rewatch from episode 1? Continue without updating tracker? Open details?")
 927			selectedOption, err := promptSelect([]SelectionOption{
 928				{Key: "rewatch", Label: "Start rewatch from episode 1"},
 929				{Key: "continue", Label: "Continue without updating tracker"},
 930				{Key: "details", Label: "Open details"},
 931			})
 932			if err != nil {
 933				Log(fmt.Sprintf("Error in completed anime prompt: %v", err))
 934				ExitCurd(fmt.Errorf("Failed to select completed anime action"))
 935			}
 936
 937			switch selectedOption.Key {
 938			case "rewatch":
 939				err = StartAnimeRewatch(user.Token, *anime)
 940				if err != nil {
 941					Log(fmt.Sprintf("Error starting anime rewatch: %v", err))
 942					ExitCurd(fmt.Errorf("Failed to move anime to rewatching"))
 943				}
 944
 945				anime.Rewatching = true
 946				anime.SkipRemoteSync = false
 947				anime.Ep.Number = 1
 948				anime.Ep.Player.PlaybackTime = 0
 949				anime.Ep.Resume = false
 950				startingRewatch = true
 951				CurdOut("Moved anime to Rewatching and restarting from episode 1.")
 952
 953				if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
 954					Log("Error refreshing anime list: " + err.Error())
 955					ExitCurd(err)
 956				}
 957			case "continue":
 958				anime.Rewatching = false
 959				anime.SkipRemoteSync = true
 960				anime.Ep.Number = 1
 961				anime.Ep.Player.PlaybackTime = 0
 962				anime.Ep.Resume = false
 963				startingRewatch = true
 964				CurdOut("Starting episode 1 without updating your tracker.")
 965			case "details":
 966				url := fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId)
 967				CurdOut(fmt.Sprintf("Opening %s", url))
 968				if err := browser.OpenURL(url); err != nil {
 969					Log(fmt.Sprintf("Error opening browser: %v", err))
 970					CurdOut("Failed to open browser.")
 971				}
 972				anime.Ep.ContinueLast = false
 973				continue
 974			case "-1":
 975				ExitCurd(nil)
 976			default:
 977				anime.Ep.ContinueLast = false
 978				continue
 979			}
 980		}
 981
 982		// Check if we need to research provider ID
 983		needsProviderSearch := false
 984		if animePointer == nil {
 985			needsProviderSearch = true
 986		} else if animePointer.ProviderName != "" && !ProviderStackContains(userCurdConfig, animePointer.ProviderName) {
 987			needsProviderSearch = true
 988		} else if animePointer.ProviderName == "" && !ProviderStackContains(userCurdConfig, "allanime") {
 989			needsProviderSearch = true
 990		}
 991
 992		// if anime not found in database or provider changed, find it in animeList
 993		if needsProviderSearch {
 994			Log("Anime not found in database for current provider, searching in animeList...")
 995			mappingOutcome, mappingErr := ResolveAnimeProviderMapping(userCurdConfig, anime, string(userQuery), selectedAnilistAnime)
 996			if mappingErr != nil {
 997				Log(fmt.Sprintf("Provider mapping failed: %v", mappingErr))
 998				ExitCurd(mappingErr)
 999			}
1000			switch mappingOutcome {
1001			case ProviderMappingBack:
1002				CurdOut("Going back to main menu...")
1003				RestoreScreen()
1004				if anime.Ep.ContinueLast {
1005					anime.Ep.ContinueLast = false
1006				}
1007				continue
1008			case ProviderMappingQuit:
1009				ExitCurd(nil)
1010			}
1011		}
1012
1013		// if anime found in database, use its playback state
1014		if animePointer != nil {
1015			if !needsProviderSearch {
1016				anime.ProviderId = animePointer.ProviderId
1017				anime.ProviderName = animePointer.ProviderName
1018			}
1019			anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
1020			if anime.Ep.Number == animePointer.Ep.Number {
1021				anime.Ep.Resume = true
1022			}
1023
1024			// If local history episode is ahead of AniList upstream, prompt user
1025			anilistEpisode := nextEpisodeFromProgress(selectedAnilistAnime.Progress)
1026			if animePointer.Ep.Number > anilistEpisode {
1027				trackerLabel := RemoteTrackingDisplayName(userCurdConfig)
1028				Log(fmt.Sprintf("Local history episode (%d) is ahead of %s episode (%d), prompting user", animePointer.Ep.Number, trackerLabel, anilistEpisode))
1029				options := []SelectionOption{
1030					{Key: "update_upstream", Label: fmt.Sprintf("Use Curd episode %d", animePointer.Ep.Number)},
1031					{Key: "use_anilist", Label: fmt.Sprintf("Use %s episode %d", trackerLabel, anilistEpisode)},
1032				}
1033				CurdOut(fmt.Sprintf("Curd has episode %d. %s has episode %d. Pick one.", animePointer.Ep.Number, trackerLabel, anilistEpisode))
1034				selectedOption, err := DynamicSelect(options)
1035				if err != nil {
1036					Log("Error in episode conflict selection: " + err.Error())
1037				} else if selectedOption.Key == "-1" {
1038					ExitCurd(nil)
1039				} else if selectedOption.Key == "update_upstream" {
1040					// Update remote progress to match local history (progress = local ep - 1, since local ep is "next to watch")
1041					progressToUpdate := animePointer.Ep.Number - 1
1042					if err := UpdateAnimeProgress(user.Token, anime.AnilistId, progressToUpdate); err != nil {
1043						Log(fmt.Sprintf("Error updating %s progress to %d: %v", trackerLabel, progressToUpdate, err))
1044					} else {
1045						Log(fmt.Sprintf("Updated %s progress to %d", trackerLabel, progressToUpdate))
1046					}
1047					anime.Ep.Number = animePointer.Ep.Number
1048					anime.Ep.Resume = true
1049				} else if selectedOption.Key == "use_anilist" {
1050					// Use remote next-episode number (already set from selectedAnilistAnime.Progress + 1)
1051					anime.Ep.Number = anilistEpisode
1052					anime.Ep.Player.PlaybackTime = 0
1053					anime.Ep.Resume = false
1054				}
1055			} else {
1056				anime.Ep.Number = animePointer.Ep.Number
1057			}
1058		}
1059
1060		if startingRewatch {
1061			anime.Ep.Player.PlaybackTime = 0
1062			anime.Ep.Resume = false
1063		}
1064
1065		if selectedAllanimeAnime.Key == "-1" {
1066			ExitCurd(nil)
1067		}
1068
1069		// If anime is not in watching list, prompt user to add it into watching list
1070		isInWatchingList := false
1071		for _, entry := range user.AnimeList.Watching {
1072			if entry.Media.ID == anime.AnilistId {
1073				isInWatchingList = true
1074				break
1075			}
1076		}
1077		if !isInWatchingList {
1078			for _, entry := range user.AnimeList.Rewatching {
1079				if entry.Media.ID == anime.AnilistId {
1080					isInWatchingList = true
1081					break
1082				}
1083			}
1084		}
1085		if anime.Rewatching {
1086			isInWatchingList = true
1087		}
1088
1089		if ShouldWriteRemoteTracking(userCurdConfig, anime) && !isInWatchingList {
1090			// Create options for the prompt
1091			options := []SelectionOption{
1092				{Key: "yes", Label: "Add to watching list"},
1093				{Key: "no", Label: "Continue without adding"},
1094			}
1095
1096			var selectedOption SelectionOption
1097			var err error
1098
1099			// Use rofi for selection
1100			selectedOption, err = DynamicSelect(options)
1101			if err != nil {
1102				Log("Error in selection: " + err.Error())
1103				ExitCurd(err)
1104			}
1105
1106			if selectedOption.Key == "yes" {
1107				err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
1108				if err != nil {
1109					Log("Error adding anime to watching list: " + err.Error())
1110					ExitCurd(err)
1111				}
1112				if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
1113					Log("Error refreshing anime list: " + err.Error())
1114					ExitCurd(err)
1115				}
1116			} else if selectedOption.Key == "-1" {
1117				ExitCurd(nil)
1118			} else if selectedOption.Key == "-2" {
1119				// Handle back button - go back to main menu
1120				CurdOut("Going back to main menu...")
1121				RestoreScreen()
1122				// If we were continuing last, disable it so we go to menu next loop
1123				if anime.Ep.ContinueLast {
1124					anime.Ep.ContinueLast = false
1125				}
1126				continue
1127			}
1128		}
1129
1130		// If upstream is ahead, update the episode number
1131		if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
1132			upstreamNextEpisode := nextEpisodeFromProgress(temp_anime.Progress)
1133			if upstreamNextEpisode > anime.Ep.Number {
1134				anime.Ep.Number = upstreamNextEpisode
1135				anime.Ep.Player.PlaybackTime = 0
1136				anime.Ep.Resume = false
1137			}
1138		}
1139
1140		if anime.TotalEpisodes == 0 {
1141			// Get updated anime data
1142			Log(selectedAllanimeAnime)
1143			updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
1144			Log(updatedAnime)
1145			if err != nil {
1146				Log(fmt.Sprintf("Error getting updated anime data: %v", err))
1147			} else {
1148				anime.TotalEpisodes = updatedAnime.TotalEpisodes
1149				Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
1150			}
1151		}
1152
1153		if anime.TotalEpisodes == 0 { // If failed to get anime data
1154			CurdOut("AniList/MAL did not return total episodes. Attempting to retrieve from provider episode list.")
1155			providerName, providerID := AnimeProviderID(anime)
1156			providerTotal, err := GetProviderTotalEpisodes(QualifyProviderID(providerName, providerID), userCurdConfig.SubOrDub)
1157			if err != nil {
1158				Log(fmt.Sprintf("Failed to retrieve total episodes from provider episode list: %v", err))
1159			} else {
1160				anime.TotalEpisodes = providerTotal
1161				CurdOut(fmt.Sprintf("Retrieved total episodes from provider: %d", anime.TotalEpisodes))
1162			}
1163		}
1164
1165		if anime.TotalEpisodes == 0 { // If provider episode list did not have a usable total
1166			CurdOut("Attempting to retrieve total episodes from anime search results.")
1167			animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
1168			if err != nil {
1169				CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
1170			} else {
1171				for _, option := range animeList {
1172					optionProviderName, optionProviderID, ok := ParseProviderQualifiedID(option.Key)
1173					if !ok {
1174						optionProviderName = configuredProviderNames(userCurdConfig)[0]
1175						optionProviderID = option.Key
1176					}
1177					if optionProviderID == anime.ProviderId && optionProviderName == CurrentAnimeProviderName(anime) {
1178						// Extract total episodes from the label
1179						if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 {
1180							anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
1181							CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
1182							break
1183						}
1184					}
1185				}
1186			}
1187
1188			if anime.TotalEpisodes == 0 {
1189				CurdOut("Still unable to determine total episodes.")
1190				CurdOut(fmt.Sprintf("Your %s progress: %d", RemoteTrackingDisplayName(userCurdConfig), selectedAnilistAnime.Progress))
1191				episodeNumber, err := promptPositiveEpisodeNumber(userCurdConfig, "Enter the episode you want to start from")
1192				if err != nil {
1193					Log("Invalid episode input: " + err.Error())
1194					ExitCurd(fmt.Errorf("Invalid episode number"))
1195				}
1196				anime.Ep.Number = episodeNumber
1197			} else {
1198				anime.Ep.Number = nextEpisodeFromProgress(selectedAnilistAnime.Progress)
1199			}
1200		} else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
1201			Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
1202			var answer string
1203			if userCurdConfig.RofiSelection {
1204				userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
1205				if err != nil {
1206					Log("Error getting user input: " + err.Error())
1207					ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1208				}
1209				answer = userInput
1210			} else {
1211				fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
1212				fmt.Scanln(&answer)
1213			}
1214			if isAffirmativeAnswer(answer) {
1215				anime.Ep.Number = 1
1216			} else {
1217				anime.Ep.Number = anime.TotalEpisodes
1218			}
1219		}
1220
1221		// If we reached here successfully, break the loop
1222		break
1223	}
1224}
1225
1226// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
1227func WriteTokenToFile(token string, filePath string) error {
1228	// Extract the directory path
1229	dir := filepath.Dir(filePath)
1230
1231	// Create all necessary parent directories
1232	if err := os.MkdirAll(dir, 0755); err != nil {
1233		return fmt.Errorf("failed to create directories: %v", err)
1234	}
1235
1236	// Write the token to the file, creating it if it doesn't exist
1237	err := os.WriteFile(filePath, []byte(token), 0644)
1238	if err != nil {
1239		return fmt.Errorf("failed to write token to file: %v", err)
1240	}
1241
1242	return nil
1243}
1244
1245func handleUnreleasedAnime(userCurdConfig *CurdConfig, user *User, anime *Anime, entry Entry) {
1246	title := entry.Media.Title.Romaji
1247	if userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" && entry.Media.Title.English != "" {
1248		title = entry.Media.Title.English
1249	}
1250	if title == "" {
1251		title = strconv.Itoa(entry.Media.ID)
1252	}
1253
1254	CurdOut(fmt.Sprintf("%s is not released yet.", title))
1255	options := []SelectionOption{}
1256	if UsesRemoteTracking(userCurdConfig) {
1257		options = append(options, SelectionOption{Key: "planning", Label: "Add to Plan to Watch"})
1258	}
1259	options = append(options,
1260		SelectionOption{Key: "details", Label: "Open AniList details"},
1261		SelectionOption{Key: "back", Label: "Back to list"},
1262	)
1263
1264	selected, err := promptSelect(options)
1265	if err != nil {
1266		Log(fmt.Sprintf("Error in unreleased anime prompt: %v", err))
1267		anime.Ep.ContinueLast = false
1268		return
1269	}
1270
1271	switch selected.Key {
1272	case "planning":
1273		if err := AddAnimeToList(entry.Media.ID, "PLANNING", user.Token); err != nil {
1274			Log(fmt.Sprintf("Error adding unreleased anime to planning: %v", err))
1275			CurdOut("Failed to add to Plan to Watch.")
1276		} else {
1277			CurdOut("Added to Plan to Watch.")
1278			if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
1279				Log("Error refreshing anime list: " + err.Error())
1280			}
1281		}
1282	case "details":
1283		url := fmt.Sprintf("https://anilist.co/anime/%d", entry.Media.ID)
1284		CurdOut(fmt.Sprintf("Opening %s", url))
1285		if err := browser.OpenURL(url); err != nil {
1286			Log(fmt.Sprintf("Error opening browser: %v", err))
1287			CurdOut("Failed to open browser.")
1288		}
1289	case "-1":
1290		ExitCurd(nil)
1291	}
1292	anime.Ep.ContinueLast = false
1293}
1294
1295func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1296	if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil {
1297		Log(fmt.Sprintf("Failed to resolve provider id: %v", err))
1298		CurdOut("Failed to resolve anime provider id: " + err.Error())
1299		os.Exit(1)
1300	}
1301
1302	// Validate inputs
1303	if anime.ProviderId == "" {
1304		CurdOut("Error: No anime ID found")
1305		os.Exit(1)
1306	}
1307	if anime.Ep.Number <= 0 {
1308		CurdOut("Error: Invalid episode number")
1309		os.Exit(1)
1310	}
1311
1312	if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1313		anime.Ep.Links = anime.Ep.NextEpisode.Links
1314		anime.Ep.StreamReferrer = ""
1315		anime.Ep.SubtitleURL = ""
1316		if anime.Ep.NextEpisode.ProviderName != "" {
1317			anime.ProviderName = anime.Ep.NextEpisode.ProviderName
1318			anime.ProviderId = anime.Ep.NextEpisode.ProviderId
1319		}
1320	} else {
1321		// Get episode link
1322		episodeResult, err := ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1323		link := episodeResult.Links
1324		if len(link) > 0 {
1325			Log(fmt.Sprintf("Links details from %s/%s: %+v", episodeResult.ProviderName, episodeResult.Mode, link))
1326		}
1327		if err != nil {
1328			linkErr := err
1329			Log(fmt.Sprintf("ResolveEpisodeURL failed: %v", linkErr))
1330			if reselectProviderAnime(userCurdConfig, anime, linkErr) {
1331				episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1332				link = episodeResult.Links
1333				if err == nil {
1334					Log(fmt.Sprintf("Successfully retrieved %s/%s episode link after provider reselect. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link)))
1335					anime.Ep.Links = link
1336					applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1337					goto episodeLinksReady
1338				}
1339				linkErr = err
1340				Log(fmt.Sprintf("ResolveEpisodeURL still failed after provider reselect: %v", linkErr))
1341			}
1342			for {
1343				switch promptEpisodeLinkFailureRecovery(userCurdConfig) {
1344				case "remap":
1345					if RemapAnimeProviderOnEpisodeFailure(userCurdConfig, anime, nil) {
1346						episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1347						link = episodeResult.Links
1348						if err == nil && len(link) > 0 {
1349							anime.Ep.Links = link
1350							applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1351							goto episodeLinksReady
1352						}
1353						if err != nil {
1354							linkErr = err
1355							Log(fmt.Sprintf("ResolveEpisodeURL failed after provider remap: %v", linkErr))
1356						}
1357					}
1358				case "episode":
1359					episodeProviderName, episodeProviderID := AnimeProviderID(anime)
1360					episodeList, listErr := EpisodesList(QualifyProviderID(episodeProviderName, episodeProviderID), userCurdConfig.SubOrDub)
1361					if listErr != nil {
1362						CurdOut("No episode list found: " + listErr.Error())
1363						Log(fmt.Sprintf("EpisodesList failed: %v", listErr))
1364						continue
1365					}
1366					if len(episodeList) == 0 {
1367						CurdOut("No episodes were returned by the current provider for this anime.")
1368						Log(fmt.Sprintf("EpisodesList returned no episodes for provider %s and id %s after ResolveEpisodeURL error: %v", episodeProviderName, episodeProviderID, linkErr))
1369						continue
1370					}
1371					episodeNumber, promptErr := promptPositiveEpisodeNumber(userCurdConfig, fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1372					if promptErr != nil {
1373						Log("Invalid episode input: " + promptErr.Error())
1374						CurdOut("Invalid episode number")
1375						continue
1376					}
1377					anime.Ep.Number = episodeNumber
1378					episodeResult, err = ResolveEpisodeURLForPlayback(*userCurdConfig, anime, anime.Ep.Number)
1379					link = episodeResult.Links
1380					if err == nil && len(link) > 0 {
1381						anime.Ep.Links = link
1382						applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1383						goto episodeLinksReady
1384					}
1385					if err != nil {
1386						linkErr = err
1387						Log(fmt.Sprintf("ResolveEpisodeURL failed for episode %d: %v", anime.Ep.Number, linkErr))
1388					} else {
1389						CurdOut("Failed to get episode link")
1390					}
1391				default:
1392					RestoreScreen()
1393					return ""
1394				}
1395			}
1396		} else {
1397			Log(fmt.Sprintf("Successfully retrieved %s/%s episode link on first try. Links count: %d", episodeResult.ProviderName, episodeResult.Mode, len(link)))
1398		}
1399		anime.Ep.Links = link
1400		applyStreamPlaybackHints(anime, anime.Ep.Links, episodeResult.LinkHints)
1401	}
1402
1403episodeLinksReady:
1404	if len(anime.Ep.Links) == 0 {
1405		CurdOut("No episode links found")
1406		RestoreScreen()
1407		return ""
1408	} else {
1409		Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links)))
1410	}
1411
1412	// Modify the goroutine in main.go where next episode links are fetched
1413	// Get next episode link in parallel
1414	go func() {
1415		nextEpNum := anime.Ep.Number + 1
1416		if nextEpNum <= anime.TotalEpisodes {
1417			// Get next canon episode number if filler skip is enabled
1418			if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) {
1419				nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum)
1420			}
1421			nextEpisode := *anime
1422			nextEpisode.ProviderId = anime.ProviderId
1423			nextEpisode.ProviderName = anime.ProviderName
1424			nextResult, err := ResolveEpisodeURL(*userCurdConfig, &nextEpisode, nextEpNum)
1425			if err != nil {
1426				Log(fmt.Sprintf("Error getting next episode link for ep %d: %v", nextEpNum, err))
1427			} else {
1428				anime.Ep.NextEpisode = NextEpisode{
1429					Number:       nextEpNum,
1430					Links:        nextResult.Links,
1431					ProviderName: nextResult.ProviderName,
1432					ProviderId:   nextResult.ProviderID,
1433					Mode:         nextResult.Mode,
1434				}
1435			}
1436		} else {
1437			Log(fmt.Sprintf("Next episode %d exceeds total episodes %d, skipping prefetch", nextEpNum, anime.TotalEpisodes))
1438		}
1439	}()
1440
1441	// Write anime.AnilistId to curd_id in the storage path
1442	idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1443	Log(fmt.Sprintf("idFilePath: %v", idFilePath))
1444	if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
1445		Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err))
1446	} else {
1447		if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
1448			Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err))
1449		}
1450	}
1451
1452	// Display starting message with cover image and episode info
1453	if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
1454		// Get the cached image path
1455		cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
1456		filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
1457		cachePath := filepath.Join(cacheDir, filename)
1458
1459		// Display the image if it exists in cache
1460		_, err := os.Stat(cachePath)
1461		if err == nil {
1462			// File exists
1463			Log(fmt.Sprintf("Image found at %s", cachePath))
1464			CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
1465		} else {
1466			// File does not exist
1467			Log(fmt.Sprintf("Image does not exist at %s", cachePath))
1468			CurdOut(fmt.Sprintf("%s - Episode %d",
1469				GetAnimeName(*anime),
1470				anime.Ep.Number))
1471
1472		}
1473	} else {
1474		CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
1475	}
1476	mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number), anime)
1477
1478	if err != nil {
1479		Log("Failed to start mpv")
1480		os.Exit(1)
1481	}
1482
1483	return mpvSocketPath
1484}
1485
1486func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
1487	if anime == nil || anime.ProviderId == "" {
1488		return nil
1489	}
1490
1491	providerName, providerID := AnimeProviderID(anime)
1492	if providerName != "animepahe" || !ProviderEnabled("animepahe") {
1493		return nil
1494	}
1495	if !ProviderStackContains(userCurdConfig, "animepahe") {
1496		return nil
1497	}
1498
1499	provider, err := ProviderByName(providerName)
1500	if err != nil {
1501		return err
1502	}
1503
1504	query := GetAnimeName(*anime)
1505	if query == "" {
1506		query = anime.Title.Romaji
1507	}
1508	if query == "" {
1509		query = anime.Title.English
1510	}
1511
1512	resolved, err := resolveProviderID(provider, providerID, query)
1513	if err != nil {
1514		return err
1515	}
1516	if resolved != "" && resolved != providerID {
1517		Log(fmt.Sprintf("Resolved Animepahe provider id %s to runtime id %s", providerID, resolved))
1518		anime.ProviderId = resolved
1519		anime.ProviderName = providerName
1520	}
1521
1522	return nil
1523}
1524
1525func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason error) bool {
1526	providerName, _ := AnimeProviderID(anime)
1527	if providerName != "animepahe" || !ProviderEnabled("animepahe") {
1528		return false
1529	}
1530
1531	if reason != nil {
1532		Log(fmt.Sprintf("Attempting Animepahe provider reselect after error: %v", reason))
1533	}
1534
1535	query := GetAnimeName(*anime)
1536	if query == "" {
1537		query = anime.Title.Romaji
1538	}
1539	if query == "" {
1540		query = anime.Title.English
1541	}
1542	if query == "" {
1543		return false
1544	}
1545
1546	options, err := SearchAnime(query, userCurdConfig.SubOrDub)
1547	if err != nil {
1548		Log(fmt.Sprintf("Animepahe provider reselect search failed for %q: %v", query, err))
1549		return false
1550	}
1551	if len(options) == 0 {
1552		Log(fmt.Sprintf("Animepahe provider reselect found no results for %q", query))
1553		return false
1554	}
1555
1556	CurdOut("The saved Animepahe mapping is stale. Please select the anime again.")
1557	var trackerEntry *Entry
1558	if anime.TotalEpisodes > 0 {
1559		trackerEntry = &Entry{Media: Media{Episodes: anime.TotalEpisodes}}
1560	}
1561	selected, err := promptProviderSearchSelection(userCurdConfig, options, trackerEntry)
1562	if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" {
1563		if err != nil {
1564			Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err))
1565		}
1566		return false
1567	}
1568
1569	if selectedProviderName, rawProviderID, ok := ParseProviderQualifiedID(selected.Key); ok {
1570		anime.ProviderName = selectedProviderName
1571		anime.ProviderId = rawProviderID
1572	} else {
1573		anime.ProviderName = "animepahe"
1574		anime.ProviderId = selected.Key
1575	}
1576	anime.Ep.NextEpisode = NextEpisode{}
1577	Log(fmt.Sprintf("Updated Animepahe ProviderId to %s after stale mapping", anime.ProviderId))
1578	return true
1579}
1580
1581func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1582	// Create storage directory if it doesn't exist
1583	storagePath = os.ExpandEnv(storagePath)
1584	if err := os.MkdirAll(storagePath, 0755); err != nil {
1585		return fmt.Errorf("failed to create storage directory: %v", err)
1586	}
1587
1588	// Base URL for downloading config files
1589	baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
1590
1591	// Check each file
1592	for _, fileName := range filesToCheck {
1593		filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
1594
1595		// Skip if file already exists
1596		if _, err := os.Stat(filePath); err == nil {
1597			continue
1598		}
1599
1600		// Download file if it doesn't exist
1601		resp, err := sharedHTTPClient.Get(baseURL + fileName)
1602		if err != nil {
1603			return fmt.Errorf("failed to download %s: %v", fileName, err)
1604		}
1605		if resp.StatusCode != http.StatusOK {
1606			resp.Body.Close()
1607			return fmt.Errorf("failed to download %s: received status code %d", fileName, resp.StatusCode)
1608		}
1609
1610		// Create the file
1611		out, err := os.Create(filePath)
1612		if err != nil {
1613			resp.Body.Close()
1614			return fmt.Errorf("failed to create file %s: %v", fileName, err)
1615		}
1616
1617		// Write the content
1618		if _, err := io.Copy(out, resp.Body); err != nil {
1619			resp.Body.Close()
1620			out.Close()
1621			return fmt.Errorf("failed to write file %s: %v", fileName, err)
1622		}
1623		resp.Body.Close()
1624		if err := out.Close(); err != nil {
1625			return fmt.Errorf("failed to close file %s: %v", fileName, err)
1626		}
1627	}
1628
1629	return nil
1630}
1631
1632func getEntriesByCategory(list AnimeList, category string) []Entry {
1633	switch category {
1634	case "ALL":
1635		// Combine all categories into one slice
1636		allEntries := make([]Entry, 0)
1637		allEntries = append(allEntries, list.Watching...)
1638		allEntries = append(allEntries, list.Completed...)
1639		allEntries = append(allEntries, list.Paused...)
1640		allEntries = append(allEntries, list.Dropped...)
1641		allEntries = append(allEntries, list.Planning...)
1642		allEntries = append(allEntries, list.Rewatching...)
1643		return allEntries
1644	case "CURRENT":
1645		currentEntries := make([]Entry, 0, len(list.Watching)+len(list.Rewatching))
1646		currentEntries = append(currentEntries, list.Watching...)
1647		currentEntries = append(currentEntries, list.Rewatching...)
1648		return currentEntries
1649	case "COMPLETED":
1650		return list.Completed
1651	case "PAUSED":
1652		return list.Paused
1653	case "DROPPED":
1654		return list.Dropped
1655	case "PLANNING":
1656		return list.Planning
1657	case "REWATCHING": // Added for completeness, though "ALL" covers it.
1658		return list.Rewatching
1659	default:
1660		return []Entry{}
1661	}
1662}
1663
1664func NextEpisodePromptCLI(userCurdConfig *CurdConfig) bool {
1665	anime := GetGlobalAnime()
1666
1667	// Show the next episode number that will be started
1668	nextEpisodeNum := anime.Ep.Number + 1
1669	isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1670	if isLastKnownEpisode {
1671		CurdOut("Finish this series?")
1672	} else {
1673		CurdOut(fmt.Sprintf("Start next episode (%d)?", nextEpisodeNum))
1674	}
1675
1676	// Create options for the selection - no "quit" option since it's built into selection menu
1677	label := fmt.Sprintf("Yes, continue to episode %d", nextEpisodeNum)
1678	if isLastKnownEpisode {
1679		label = "Yes, finish series"
1680	}
1681	options := []SelectionOption{
1682		{Key: "yes", Label: label},
1683	}
1684
1685	// Use DynamicSelect for CLI mode
1686	selectedOption, err := DynamicSelect(options)
1687	if err != nil {
1688		Log(fmt.Sprintf("Error in CLI next episode prompt selection: %v", err))
1689		return false
1690	}
1691
1692	Log(fmt.Sprintf("CLI User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1693
1694	if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1695		// User selected to quit/back via the built-in option
1696		CurdOut("Exiting")
1697		return false
1698	}
1699
1700	return selectedOption.Key == "yes"
1701}
1702
1703// NextEpisodePromptContinuous provides a continuous next episode prompt for CLI mode
1704// This runs throughout the episode duration and handles completion logic
1705func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1706	anime := GetGlobalAnime()
1707
1708	for {
1709		// Check if episode has started
1710		if !anime.Ep.Started {
1711			time.Sleep(1 * time.Second)
1712			continue
1713		}
1714
1715		// Show the next episode number that will be started
1716		nextEpisodeNum := anime.Ep.Number + 1
1717		isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1718		if isLastKnownEpisode {
1719			CurdOut("Finish this series or quit?")
1720		} else {
1721			CurdOut(fmt.Sprintf("Continue to next episode (%d) or quit?", nextEpisodeNum))
1722		}
1723
1724		// Create options for the selection - no "quit" option since it's built into selection menu
1725		label := "Yes, start next episode now"
1726		if isLastKnownEpisode {
1727			label = "Yes, finish series"
1728		}
1729		options := []SelectionOption{
1730			{Key: "yes", Label: label},
1731		}
1732
1733		// Use DynamicSelect for CLI mode
1734		selectedOption, err := DynamicSelect(options)
1735		if err != nil {
1736			Log(fmt.Sprintf("Error in CLI continuous next episode prompt: %v", err))
1737			break
1738		}
1739
1740		Log(fmt.Sprintf("CLI Continuous User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1741
1742		if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1743			// User selected to quit/back via the built-in option
1744
1745			// Check completion percentage
1746			percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
1747
1748			if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
1749				// Episode is considered completed, mark it and update progress
1750				anime.Ep.IsCompleted = true
1751
1752				// Handle completion if this was the last episode
1753				if anime.Ep.Number == anime.TotalEpisodes {
1754					HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
1755				}
1756
1757				// Update local database
1758				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 {
1759					Log("Error updating local database on quit: " + updateErr.Error())
1760				}
1761
1762				if !(anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && anime.Rewatching) {
1763					completedEpisode := anime.Ep.Number
1764					go func(progressEpisode int) {
1765						if progressErr := UpdateAnimeProgress(userToken, anime.AnilistId, progressEpisode); progressErr != nil {
1766							Log("Error updating Anilist progress on quit: " + progressErr.Error())
1767						}
1768					}(completedEpisode)
1769				}
1770
1771				CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched))
1772			} else {
1773				CurdOut(fmt.Sprintf("Episode not completed (%.1f%% watched). Exiting.", percentageWatched))
1774			}
1775
1776			ExitMPV(anime.Ep.Player.SocketPath)
1777			ExitCurd(nil)
1778			return
1779		}
1780
1781		if selectedOption.Key == "yes" {
1782			// User wants to start next episode immediately
1783			anime.Ep.IsCompleted = true
1784			socketPath := anime.Ep.Player.SocketPath
1785			if anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes {
1786				ExitMPV(socketPath)
1787			}
1788			StartNextEpisode(anime, userCurdConfig, databaseFile, userToken)
1789			ExitMPV(socketPath)
1790			return // Exit this function, let the main loop handle next episode
1791		}
1792	}
1793}
1794
1795// Simple next episode prompt for Rofi mode - just asks if user wants to continue
1796func NextEpisodePromptRofi(userCurdConfig *CurdConfig) bool {
1797	anime := GetGlobalAnime()
1798
1799	// Show the next episode number that will be started
1800	nextEpisodeNum := anime.Ep.Number + 1
1801	isLastKnownEpisode := anime.TotalEpisodes > 0 && anime.Ep.Number >= anime.TotalEpisodes
1802
1803	// Create options for the selection
1804	label := fmt.Sprintf("Yes, start episode %d", nextEpisodeNum)
1805	if isLastKnownEpisode {
1806		label = "Yes, finish series"
1807	}
1808	options := []SelectionOption{
1809		{Key: "yes", Label: label},
1810	}
1811
1812	// Use DynamicSelect for Rofi mode
1813	selectedOption, err := DynamicSelect(options)
1814	if err != nil {
1815		Log(fmt.Sprintf("Error in next episode prompt selection: %v", err))
1816		return false
1817	}
1818
1819	Log(fmt.Sprintf("Rofi User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1820
1821	return selectedOption.Key == "yes"
1822}
1823
1824// StartNextEpisode handles the logic for starting the next episode
1825// It updates the episode number, resets necessary flags, and handles database updates
1826func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1827	// Save previous episode number for progress update
1828	prevEpisode := anime.Ep.Number
1829
1830	// Check if we just completed the last episode
1831	if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1832		// Handle scoring and completion for the last episode
1833		HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
1834
1835		if !anime.Rewatching {
1836			err := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1837			if err != nil {
1838				Log("Error updating Anilist progress: " + err.Error())
1839			}
1840		}
1841		// Note: UpdateAnimeProgress already outputs a message on success
1842
1843		CurdOut("Series completed!")
1844		ExitCurd(nil)
1845		return
1846	}
1847
1848	// Increment episode number
1849	anime.Ep.Number++
1850
1851	// Check if we've reached the end of the series
1852	if anime.TotalEpisodes > 0 && anime.Ep.Number > anime.TotalEpisodes {
1853		CurdOut("Reached end of series")
1854		ExitCurd(nil)
1855		return
1856	}
1857
1858	// Use prefetched links if available for the next episode
1859	if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1860		anime.Ep.Links = anime.Ep.NextEpisode.Links
1861		anime.Ep.StreamReferrer = ""
1862		anime.Ep.SubtitleURL = ""
1863		if anime.Ep.NextEpisode.ProviderName != "" {
1864			anime.ProviderName = anime.Ep.NextEpisode.ProviderName
1865			anime.ProviderId = anime.Ep.NextEpisode.ProviderId
1866		}
1867		Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number))
1868	} else {
1869		// Clear links to force fetching new ones
1870		anime.Ep.Links = []string{}
1871		Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
1872	}
1873
1874	// Reset episode flags
1875	anime.Ep.Started = false
1876	anime.Ep.IsCompleted = false
1877
1878	// Log the transition
1879	Log("Completed episode, starting next.")
1880
1881	// Update local database
1882	err := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, GetAnimeName(*anime), CurrentAnimeProviderName(anime))
1883	if err != nil {
1884		Log("Error updating local database: " + err.Error())
1885	}
1886
1887	go func() {
1888		if progressErr := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode); progressErr != nil {
1889			Log("Error updating Anilist progress: " + progressErr.Error())
1890		}
1891	}()
1892
1893	// Output message to user
1894	CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
1895}
1896
1897// HandleLastEpisodeCompletion handles scoring and completion for the last episode
1898func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
1899	if anime.TotalEpisodes <= 0 || anime.Ep.Number != anime.TotalEpisodes {
1900		return
1901	}
1902
1903	summary := []string{}
1904	canWriteRemote := ShouldWriteRemoteTracking(userCurdConfig, anime)
1905
1906	if userCurdConfig.ScoreOnCompletion && !anime.IsAiring && canWriteRemote {
1907		CurdOut("You've completed this anime! Would you like to rate it?")
1908
1909		scoreOptions := []SelectionOption{
1910			{Key: "yes", Label: "Yes, rate this anime"},
1911			{Key: "no", Label: "No, skip rating"},
1912		}
1913
1914		selectedOption, err := DynamicSelect(scoreOptions)
1915		if err != nil {
1916			Log(fmt.Sprintf("Error in score prompt selection: %v", err))
1917		} else if selectedOption.Key == "yes" {
1918			err = RateAnime(userToken, anime.AnilistId)
1919			if err != nil {
1920				Log(fmt.Sprintf("Error rating anime: %v", err))
1921				CurdOut("Failed to rate anime")
1922				summary = append(summary, "rating failed")
1923			} else {
1924				CurdOut("Anime rated successfully!")
1925				summary = append(summary, "rating saved")
1926			}
1927		} else {
1928			summary = append(summary, "rating skipped")
1929		}
1930		// Back (-2) and no are treated as skip
1931	} else {
1932		summary = append(summary, "rating skipped")
1933	}
1934
1935	if !anime.IsAiring && canWriteRemote {
1936		if anime.Rewatching {
1937			err := CompleteAnimeRewatch(userToken, *anime)
1938			if err != nil {
1939				Log("Error completing anime rewatch: " + err.Error())
1940				summary = append(summary, "rewatch completion failed")
1941			} else {
1942				summary = append(summary, "rewatch completed")
1943			}
1944		} else {
1945			err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED")
1946			if err != nil {
1947				Log("Error updating anime status to completed: " + err.Error())
1948				summary = append(summary, "status update failed")
1949			} else {
1950				summary = append(summary, "marked completed")
1951			}
1952		}
1953	} else if !anime.IsAiring {
1954		summary = append(summary, "tracker updates skipped")
1955	}
1956
1957	if sequelSummary := handleSequelCheck(userCurdConfig, anime, userToken); sequelSummary != "" {
1958		summary = append(summary, sequelSummary)
1959	}
1960	if len(summary) > 0 {
1961		CurdOut("Completion summary: " + strings.Join(summary, "; "))
1962	}
1963}
1964
1965// handleSequelCheck checks for sequels and prompts the user accordingly
1966func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken string) (summary string) {
1967	if !ShouldWriteRemoteTracking(userCurdConfig, anime) {
1968		return "sequel check skipped"
1969	}
1970
1971	// Recover from any panics in this function to prevent crashes
1972	defer func() {
1973		if r := recover(); r != nil {
1974			Log(fmt.Sprintf("Recovered from panic in handleSequelCheck: %v", r))
1975			summary = "sequel check failed"
1976		}
1977	}()
1978
1979	// Fetch sequel information
1980	sequels, err := GetAnimeSequel(anime.AnilistId, userToken)
1981	if err != nil {
1982		Log(fmt.Sprintf("Error fetching sequel information: %v", err))
1983		return "sequel check failed"
1984	}
1985
1986	if len(sequels) == 0 {
1987		Log("No sequel found for this anime")
1988		return "no sequel found"
1989	}
1990
1991	sequel := &sequels[0]
1992	if len(sequels) > 1 {
1993		selectedSequel, ok := selectSequel(userCurdConfig, sequels)
1994		if !ok {
1995			return "sequel skipped"
1996		}
1997		sequel = selectedSequel
1998	}
1999
2000	return promptSequelAction(userCurdConfig, sequel, userToken)
2001}
2002
2003func selectSequel(userCurdConfig *CurdConfig, sequels []SequelInfo) (*SequelInfo, bool) {
2004	CurdOut("Multiple sequels found.")
2005	options := make([]SelectionOption, 0, len(sequels)+1)
2006	for i := range sequels {
2007		title := sequelDisplayTitle(userCurdConfig, &sequels[i])
2008		status := strings.ToLower(strings.ReplaceAll(sequels[i].Status, "_", " "))
2009		options = append(options, SelectionOption{
2010			Key:   strconv.Itoa(i),
2011			Label: fmt.Sprintf("%s (%s)", title, status),
2012		})
2013	}
2014	options = append(options, SelectionOption{Key: "skip", Label: "Skip"})
2015
2016	selected, err := promptSelect(options)
2017	if err != nil {
2018		Log(fmt.Sprintf("Error selecting sequel: %v", err))
2019		return nil, false
2020	}
2021	if selected.Key == "skip" || selected.Key == "-1" || selected.Key == "-2" {
2022		return nil, false
2023	}
2024	index, err := strconv.Atoi(selected.Key)
2025	if err != nil || index < 0 || index >= len(sequels) {
2026		return nil, false
2027	}
2028	return &sequels[index], true
2029}
2030
2031func sequelDisplayTitle(userCurdConfig *CurdConfig, sequel *SequelInfo) string {
2032	if sequel == nil {
2033		return ""
2034	}
2035	if userCurdConfig != nil && userCurdConfig.AnimeNameLanguage == "english" && sequel.Title.English != "" {
2036		return sequel.Title.English
2037	}
2038	if sequel.Title.Romaji != "" {
2039		return sequel.Title.Romaji
2040	}
2041	return strconv.Itoa(sequel.ID)
2042}
2043
2044func promptSequelAction(userCurdConfig *CurdConfig, sequel *SequelInfo, userToken string) string {
2045	if sequel == nil {
2046		return ""
2047	}
2048
2049	sequelTitle := sequelDisplayTitle(userCurdConfig, sequel)
2050	Log(fmt.Sprintf("Found sequel: %s (ID: %d)", sequelTitle, sequel.ID))
2051
2052	currentUser := GetGlobalUser()
2053	userAnimeList := AnimeList{}
2054	if currentUser != nil {
2055		userAnimeList = currentUser.AnimeList
2056	}
2057	sequelStatus, isInList := "", false
2058	if hasAnyEntries(userAnimeList) {
2059		sequelStatus, isInList = FindSequelInAnimeList(userAnimeList, sequel.ID)
2060	}
2061
2062	if isInList {
2063		CurdOut(fmt.Sprintf("Sequel found: %s (%s)", sequelTitle, sequelStatus))
2064	} else {
2065		CurdOut(fmt.Sprintf("Sequel found: %s", sequelTitle))
2066	}
2067
2068	options := []SelectionOption{}
2069	if sequel.Status != "NOT_YET_RELEASED" {
2070		if !isInList || sequelStatus == "PLANNING" || sequelStatus == "PAUSED" || sequelStatus == "DROPPED" {
2071			options = append(options, SelectionOption{Key: "watching", Label: "Add to Watching"})
2072		}
2073	}
2074	if !isInList || sequelStatus != "PLANNING" {
2075		options = append(options, SelectionOption{Key: "planning", Label: "Add to Plan to Watch"})
2076	}
2077	options = append(options,
2078		SelectionOption{Key: "details", Label: "Open AniList details"},
2079		SelectionOption{Key: "skip", Label: "Skip"},
2080	)
2081
2082	selected, err := promptSelect(options)
2083	if err != nil {
2084		Log(fmt.Sprintf("Error in sequel action prompt: %v", err))
2085		return "sequel action failed"
2086	}
2087
2088	switch selected.Key {
2089	case "watching":
2090		if err := AddAnimeToList(sequel.ID, "CURRENT", userToken); err != nil {
2091			Log(fmt.Sprintf("Error adding sequel to watching list: %v", err))
2092			CurdOut("Failed to add sequel to Watching.")
2093			return "sequel add failed"
2094		} else {
2095			CurdOut(fmt.Sprintf("Added '%s' to Watching.", sequelTitle))
2096			return "sequel added to Watching"
2097		}
2098	case "planning":
2099		if err := AddAnimeToList(sequel.ID, "PLANNING", userToken); err != nil {
2100			Log(fmt.Sprintf("Error adding sequel to planning list: %v", err))
2101			CurdOut("Failed to add sequel to Plan to Watch.")
2102			return "sequel add failed"
2103		} else {
2104			CurdOut(fmt.Sprintf("Added '%s' to Plan to Watch.", sequelTitle))
2105			return "sequel added to Plan to Watch"
2106		}
2107	case "details":
2108		url := sequel.SiteURL
2109		if url == "" {
2110			url = fmt.Sprintf("https://anilist.co/anime/%d", sequel.ID)
2111		}
2112		CurdOut(fmt.Sprintf("Opening %s", url))
2113		if err := browser.OpenURL(url); err != nil {
2114			Log(fmt.Sprintf("Error opening browser: %v", err))
2115			CurdOut("Failed to open browser.")
2116			return "sequel details failed"
2117		}
2118		return "sequel details opened"
2119	case "skip", "-1", "-2":
2120		Log("User skipped sequel action")
2121	}
2122	return "sequel skipped"
2123}
2124
2125// ChangeProvider allows the user to switch the anime provider
2126func ChangeProvider(userCurdConfig *CurdConfig) {
2127	options := providerSelectionOptions()
2128	if len(options) == 0 {
2129		CurdOut("\nNo providers are currently enabled.\n")
2130		return
2131	}
2132
2133	selected, err := DynamicSelect(options)
2134	if err != nil || selected.Key == "-1" || selected.Key == "-2" {
2135		return
2136	}
2137
2138	// Update the config
2139	providerValue := canonicalProviderConfigValue(selected.Key)
2140	userCurdConfig.Provider = providerValue
2141	CurrentProvider = nil // reset the provider instance
2142
2143	// Save to config file
2144	configPath := GlobalConfigPath
2145	configMap, err := LoadConfigFromFile(configPath)
2146	if err == nil {
2147		configMap["Provider"] = providerValue
2148		SaveConfigToFile(configPath, configMap)
2149	}
2150
2151	CurdOut(fmt.Sprintf("\nProvider successfully changed to %s.\n", selected.Label))
2152	time.Sleep(1 * time.Second)
2153}