internal/curd.go

1914 lines · 61647 bytes

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