internal/curd.go

1948 lines · 63427 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			// If local history episode is ahead of AniList upstream, prompt user
1042			anilistEpisode := selectedAnilistAnime.Progress + 1
1043			if animePointer.Ep.Number > anilistEpisode {
1044				Log(fmt.Sprintf("Local history episode (%d) is ahead of AniList episode (%d), prompting user", animePointer.Ep.Number, anilistEpisode))
1045				options := []SelectionOption{
1046					{Key: "update_upstream", Label: fmt.Sprintf("Update AniList to episode %d (local history)", animePointer.Ep.Number-1)},
1047					{Key: "use_anilist", Label: fmt.Sprintf("Use AniList episode %d", anilistEpisode)},
1048				}
1049				CurdOut(fmt.Sprintf("Local history (ep %d) is ahead of AniList (ep %d).", animePointer.Ep.Number, anilistEpisode))
1050				selectedOption, err := DynamicSelect(options)
1051				if err != nil {
1052					Log("Error in episode conflict selection: " + err.Error())
1053				} else if selectedOption.Key == "-1" {
1054					ExitCurd(nil)
1055				} else if selectedOption.Key == "update_upstream" {
1056					// Update AniList progress to match local history (progress = local ep - 1, since local ep is "next to watch")
1057					progressToUpdate := animePointer.Ep.Number - 1
1058					if err := UpdateAnimeProgress(user.Token, anime.AnilistId, progressToUpdate); err != nil {
1059						Log(fmt.Sprintf("Error updating AniList progress to %d: %v", progressToUpdate, err))
1060					} else {
1061						Log(fmt.Sprintf("Updated AniList progress to %d", progressToUpdate))
1062					}
1063					anime.Ep.Number = animePointer.Ep.Number
1064					anime.Ep.Resume = true
1065				} else if selectedOption.Key == "use_anilist" {
1066					// Use AniList episode number (already set from selectedAnilistAnime.Progress + 1)
1067					anime.Ep.Number = anilistEpisode
1068					anime.Ep.Player.PlaybackTime = 0
1069					anime.Ep.Resume = false
1070				}
1071			} else {
1072				anime.Ep.Number = animePointer.Ep.Number
1073			}
1074		}
1075
1076		if startingRewatch {
1077			anime.Ep.Player.PlaybackTime = 0
1078			anime.Ep.Resume = false
1079		}
1080
1081		if selectedAllanimeAnime.Key == "-1" {
1082			ExitCurd(nil)
1083		}
1084
1085		// If anime is not in watching list, prompt user to add it into watching list
1086		isInWatchingList := false
1087		for _, entry := range user.AnimeList.Watching {
1088			if entry.Media.ID == anime.AnilistId {
1089				isInWatchingList = true
1090				break
1091			}
1092		}
1093		if !isInWatchingList {
1094			for _, entry := range user.AnimeList.Rewatching {
1095				if entry.Media.ID == anime.AnilistId {
1096					isInWatchingList = true
1097					break
1098				}
1099			}
1100		}
1101		if anime.Rewatching {
1102			isInWatchingList = true
1103		}
1104
1105		if !isInWatchingList {
1106			// Create options for the prompt
1107			options := []SelectionOption{
1108				{Key: "yes", Label: "Add to watching list"},
1109				{Key: "no", Label: "Continue without adding"},
1110			}
1111
1112			var selectedOption SelectionOption
1113			var err error
1114
1115			// Use rofi for selection
1116			selectedOption, err = DynamicSelect(options)
1117			if err != nil {
1118				Log("Error in selection: " + err.Error())
1119				ExitCurd(err)
1120			}
1121
1122			if selectedOption.Key == "yes" {
1123				err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
1124				if err != nil {
1125					Log("Error adding anime to watching list: " + err.Error())
1126					ExitCurd(err)
1127				}
1128				if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
1129					Log("Error refreshing anime list: " + err.Error())
1130					ExitCurd(err)
1131				}
1132			} else if selectedOption.Key == "-1" {
1133				ExitCurd(nil)
1134			} else if selectedOption.Key == "-2" {
1135				// Handle back button - go back to main menu
1136				CurdOut("Going back to main menu...")
1137				RestoreScreen()
1138				// If we were continuing last, disable it so we go to menu next loop
1139				if anime.Ep.ContinueLast {
1140					anime.Ep.ContinueLast = false
1141				}
1142				continue
1143			}
1144		}
1145
1146		// If upstream is ahead, update the episode number
1147		if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
1148			if temp_anime.Progress > anime.Ep.Number {
1149				anime.Ep.Number = temp_anime.Progress
1150				anime.Ep.Player.PlaybackTime = 0
1151				anime.Ep.Resume = false
1152			}
1153		}
1154
1155		if anime.TotalEpisodes == 0 {
1156			// Get updated anime data
1157			Log(selectedAllanimeAnime)
1158			updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
1159			Log(updatedAnime)
1160			if err != nil {
1161				Log(fmt.Sprintf("Error getting updated anime data: %v", err))
1162			} else {
1163				anime.TotalEpisodes = updatedAnime.TotalEpisodes
1164				Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
1165			}
1166		}
1167
1168		if anime.TotalEpisodes == 0 { // If failed to get anime data
1169			CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
1170			animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
1171			if err != nil {
1172				CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
1173			} else {
1174				for _, option := range animeList {
1175					if option.Key == anime.AllanimeId {
1176						// Extract total episodes from the label
1177						if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 {
1178							anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
1179							CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
1180							break
1181						}
1182					}
1183				}
1184			}
1185
1186			if anime.TotalEpisodes == 0 {
1187				CurdOut("Still unable to determine total episodes.")
1188				CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
1189				var episodeNumber int
1190				if userCurdConfig.RofiSelection {
1191					userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
1192					if err != nil {
1193						Log("Error getting user input: " + err.Error())
1194						ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1195					}
1196					episodeNumber, err = strconv.Atoi(userInput)
1197				} else {
1198					fmt.Print("Enter the episode you want to start from: ")
1199					fmt.Scanln(&episodeNumber)
1200				}
1201				anime.Ep.Number = episodeNumber
1202			} else {
1203				anime.Ep.Number = selectedAnilistAnime.Progress + 1
1204			}
1205		} else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
1206			Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
1207			var answer string
1208			if userCurdConfig.RofiSelection {
1209				userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
1210				if err != nil {
1211					Log("Error getting user input: " + err.Error())
1212					ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1213				}
1214				answer = userInput
1215			} else {
1216				fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
1217				fmt.Scanln(&answer)
1218			}
1219			if answer == "y" {
1220				anime.Ep.Number = 1
1221			} else {
1222				anime.Ep.Number = anime.TotalEpisodes
1223			}
1224		}
1225
1226		// If we reached here successfully, break the loop
1227		break
1228	}
1229}
1230
1231// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
1232func WriteTokenToFile(token string, filePath string) error {
1233	// Extract the directory path
1234	dir := filepath.Dir(filePath)
1235
1236	// Create all necessary parent directories
1237	if err := os.MkdirAll(dir, 0755); err != nil {
1238		return fmt.Errorf("failed to create directories: %v", err)
1239	}
1240
1241	// Write the token to the file, creating it if it doesn't exist
1242	err := os.WriteFile(filePath, []byte(token), 0644)
1243	if err != nil {
1244		return fmt.Errorf("failed to write token to file: %v", err)
1245	}
1246
1247	return nil
1248}
1249
1250func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1251
1252	// Validate inputs
1253	if anime.AllanimeId == "" {
1254		CurdOut("Error: No anime ID found")
1255		os.Exit(1)
1256	}
1257	if anime.Ep.Number <= 0 {
1258		CurdOut("Error: Invalid episode number")
1259		os.Exit(1)
1260	}
1261
1262	if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1263		anime.Ep.Links = anime.Ep.NextEpisode.Links
1264	} else {
1265		// Get episode link
1266		link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1267		if len(link) > 0 {
1268			Log(fmt.Sprintf("Links details: %+v", link))
1269		}
1270		if err != nil {
1271			// If unable to get episode link automatically get manually
1272			episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
1273			if err != nil {
1274				CurdOut("No episode list found")
1275				RestoreScreen()
1276				os.Exit(1)
1277			}
1278			if userCurdConfig.RofiSelection {
1279				userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1280				if err != nil {
1281					Log("Error getting user input: " + err.Error())
1282					ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1283				}
1284				anime.Ep.Number, err = strconv.Atoi(userInput)
1285			} else {
1286				CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1287				fmt.Scanln(&anime.Ep.Number)
1288			}
1289			link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1290			if err != nil {
1291				CurdOut("Failed to get episode link")
1292				os.Exit(1)
1293			}
1294		} else {
1295			Log(fmt.Sprintf("Successfully retrieved episode link on first try. Links count: %d", len(link)))
1296		}
1297		anime.Ep.Links = link
1298	}
1299
1300	if len(anime.Ep.Links) == 0 {
1301		CurdOut("No episode links found")
1302		os.Exit(1)
1303	} else {
1304		Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links)))
1305	}
1306
1307	// Modify the goroutine in main.go where next episode links are fetched
1308	// Get next episode link in parallel
1309	go func() {
1310		nextEpNum := anime.Ep.Number + 1
1311		if nextEpNum <= anime.TotalEpisodes {
1312			// Get next canon episode number if filler skip is enabled
1313			if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) {
1314				nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum)
1315			}
1316			nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum)
1317			if err != nil {
1318				Log(fmt.Sprintf("Error getting next episode link for ep %d: %v", nextEpNum, err))
1319			} else {
1320				anime.Ep.NextEpisode = NextEpisode{
1321					Number: nextEpNum,
1322					Links:  nextLinks,
1323				}
1324			}
1325		} else {
1326			Log(fmt.Sprintf("Next episode %d exceeds total episodes %d, skipping prefetch", nextEpNum, anime.TotalEpisodes))
1327		}
1328	}()
1329
1330	// Write anime.AnilistId to curd_id in the storage path
1331	idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1332	Log(fmt.Sprintf("idFilePath: %v", idFilePath))
1333	if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
1334		Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err))
1335	} else {
1336		if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
1337			Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err))
1338		}
1339	}
1340
1341	// Display starting message with cover image and episode info
1342	if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
1343		// Get the cached image path
1344		cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
1345		filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
1346		cachePath := filepath.Join(cacheDir, filename)
1347
1348		// Display the image if it exists in cache
1349		_, err := os.Stat(cachePath)
1350		if err == nil {
1351			// File exists
1352			Log(fmt.Sprintf("Image found at %s", cachePath))
1353			CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
1354		} else {
1355			// File does not exist
1356			Log(fmt.Sprintf("Image does not exist at %s", cachePath))
1357			CurdOut(fmt.Sprintf("%s - Episode %d",
1358				GetAnimeName(*anime),
1359				anime.Ep.Number))
1360
1361		}
1362	} else {
1363		CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
1364	}
1365	mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number), anime)
1366
1367	if err != nil {
1368		Log("Failed to start mpv")
1369		os.Exit(1)
1370	}
1371
1372	return mpvSocketPath
1373}
1374
1375func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1376	// Create storage directory if it doesn't exist
1377	storagePath = os.ExpandEnv(storagePath)
1378	if err := os.MkdirAll(storagePath, 0755); err != nil {
1379		return fmt.Errorf("failed to create storage directory: %v", err)
1380	}
1381
1382	// Base URL for downloading config files
1383	baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
1384
1385	// Check each file
1386	for _, fileName := range filesToCheck {
1387		filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
1388
1389		// Skip if file already exists
1390		if _, err := os.Stat(filePath); err == nil {
1391			continue
1392		}
1393
1394		// Download file if it doesn't exist
1395		resp, err := http.Get(baseURL + fileName)
1396		if err != nil {
1397			return fmt.Errorf("failed to download %s: %v", fileName, err)
1398		}
1399		defer resp.Body.Close()
1400
1401		// Create the file
1402		out, err := os.Create(filePath)
1403		if err != nil {
1404			return fmt.Errorf("failed to create file %s: %v", fileName, err)
1405		}
1406		defer out.Close()
1407
1408		// Write the content
1409		if _, err := io.Copy(out, resp.Body); err != nil {
1410			return fmt.Errorf("failed to write file %s: %v", fileName, err)
1411		}
1412	}
1413
1414	return nil
1415}
1416
1417func getEntriesByCategory(list AnimeList, category string) []Entry {
1418	switch category {
1419	case "ALL":
1420		// Combine all categories into one slice
1421		allEntries := make([]Entry, 0)
1422		allEntries = append(allEntries, list.Watching...)
1423		allEntries = append(allEntries, list.Completed...)
1424		allEntries = append(allEntries, list.Paused...)
1425		allEntries = append(allEntries, list.Dropped...)
1426		allEntries = append(allEntries, list.Planning...)
1427		allEntries = append(allEntries, list.Rewatching...)
1428		return allEntries
1429	case "CURRENT":
1430		currentEntries := make([]Entry, 0, len(list.Watching)+len(list.Rewatching))
1431		currentEntries = append(currentEntries, list.Watching...)
1432		currentEntries = append(currentEntries, list.Rewatching...)
1433		return currentEntries
1434	case "COMPLETED":
1435		return list.Completed
1436	case "PAUSED":
1437		return list.Paused
1438	case "DROPPED":
1439		return list.Dropped
1440	case "PLANNING":
1441		return list.Planning
1442	case "REWATCHING": // Added for completeness, though "ALL" covers it.
1443		return list.Rewatching
1444	default:
1445		return []Entry{}
1446	}
1447}
1448
1449func NextEpisodePromptCLI(userCurdConfig *CurdConfig) bool {
1450	anime := GetGlobalAnime()
1451
1452	// Show the next episode number that will be started
1453	nextEpisodeNum := anime.Ep.Number + 1
1454	CurdOut(fmt.Sprintf("Start next episode (%d)?", nextEpisodeNum))
1455
1456	// Create options for the selection - no "quit" option since it's built into selection menu
1457	options := []SelectionOption{
1458		{Key: "yes", Label: fmt.Sprintf("Yes, continue to episode %d", nextEpisodeNum)},
1459	}
1460
1461	// Use DynamicSelect for CLI mode
1462	selectedOption, err := DynamicSelect(options)
1463	if err != nil {
1464		Log(fmt.Sprintf("Error in CLI next episode prompt selection: %v", err))
1465		return false
1466	}
1467
1468	Log(fmt.Sprintf("CLI User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1469
1470	if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1471		// User selected to quit/back via the built-in option
1472		CurdOut("Exiting")
1473		return false
1474	}
1475
1476	return selectedOption.Key == "yes"
1477}
1478
1479// NextEpisodePromptContinuous provides a continuous next episode prompt for CLI mode
1480// This runs throughout the episode duration and handles completion logic
1481func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1482	anime := GetGlobalAnime()
1483
1484	for {
1485		// Check if episode has started
1486		if !anime.Ep.Started {
1487			time.Sleep(1 * time.Second)
1488			continue
1489		}
1490
1491		// Show the next episode number that will be started
1492		nextEpisodeNum := anime.Ep.Number + 1
1493		CurdOut(fmt.Sprintf("Continue to next episode (%d) or quit?", nextEpisodeNum))
1494
1495		// Create options for the selection - no "quit" option since it's built into selection menu
1496		options := []SelectionOption{
1497			{Key: "yes", Label: "Yes, start next episode now"},
1498		}
1499
1500		// Use DynamicSelect for CLI mode
1501		selectedOption, err := DynamicSelect(options)
1502		if err != nil {
1503			Log(fmt.Sprintf("Error in CLI continuous next episode prompt: %v", err))
1504			break
1505		}
1506
1507		Log(fmt.Sprintf("CLI Continuous User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1508
1509		if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1510			// User selected to quit/back via the built-in option
1511
1512			// Check completion percentage
1513			percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
1514
1515			if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
1516				// Episode is considered completed, mark it and update progress
1517				anime.Ep.IsCompleted = true
1518
1519				// Handle completion if this was the last episode
1520				if anime.Ep.Number == anime.TotalEpisodes {
1521					HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
1522				}
1523
1524				// Update local database
1525				err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime))
1526				if err != nil {
1527					Log("Error updating local database on quit: " + err.Error())
1528				}
1529
1530				go func() {
1531					err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number)
1532					if err != nil {
1533						Log("Error updating Anilist progress on quit: " + err.Error())
1534					}
1535				}()
1536
1537				CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched))
1538			} else {
1539				CurdOut(fmt.Sprintf("Episode not completed (%.1f%% watched). Exiting.", percentageWatched))
1540			}
1541
1542			ExitMPV(anime.Ep.Player.SocketPath)
1543			ExitCurd(nil)
1544			return
1545		}
1546
1547		if selectedOption.Key == "yes" {
1548			// User wants to start next episode immediately
1549			anime.Ep.IsCompleted = true
1550
1551			// Update database with completed episode first
1552			err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime))
1553			if err != nil {
1554				Log("Error updating local database with completed episode: " + err.Error())
1555			}
1556
1557			go func() {
1558				err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number)
1559				if err != nil {
1560					Log("Error updating Anilist progress: " + err.Error())
1561				}
1562			}()
1563
1564			// Increment to next episode and update database with next episode number and 0 playback time
1565			anime.Ep.Number++
1566
1567			// Use prefetched links if available for the next episode
1568			if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1569				anime.Ep.Links = anime.Ep.NextEpisode.Links
1570				Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number))
1571			} else {
1572				// Clear links to force fetching new ones
1573				anime.Ep.Links = []string{}
1574				Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
1575			}
1576
1577			err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, GetAnimeName(*anime))
1578			if err != nil {
1579				Log("Error updating local database with next episode: " + err.Error())
1580			}
1581
1582			CurdOut("Starting next episode now...")
1583			ExitMPV(anime.Ep.Player.SocketPath)
1584			return // Exit this function, let the main loop handle next episode
1585		}
1586	}
1587}
1588
1589// Simple next episode prompt for Rofi mode - just asks if user wants to continue
1590func NextEpisodePromptRofi(userCurdConfig *CurdConfig) bool {
1591	anime := GetGlobalAnime()
1592
1593	// Show the next episode number that will be started
1594	nextEpisodeNum := anime.Ep.Number + 1
1595
1596	// Create options for the selection
1597	options := []SelectionOption{
1598		{Key: "yes", Label: fmt.Sprintf("Yes, start episode %d", nextEpisodeNum)},
1599	}
1600
1601	// Use DynamicSelect for Rofi mode
1602	selectedOption, err := DynamicSelect(options)
1603	if err != nil {
1604		Log(fmt.Sprintf("Error in next episode prompt selection: %v", err))
1605		return false
1606	}
1607
1608	Log(fmt.Sprintf("Rofi User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1609
1610	return selectedOption.Key == "yes"
1611}
1612
1613// StartNextEpisode handles the logic for starting the next episode
1614// It updates the episode number, resets necessary flags, and handles database updates
1615func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1616	// Save previous episode number for progress update
1617	prevEpisode := anime.Ep.Number
1618
1619	// Check if we just completed the last episode
1620	if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1621		// Handle scoring and completion for the last episode
1622		HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
1623
1624		err := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1625		if err != nil {
1626			Log("Error updating Anilist progress: " + err.Error())
1627		}
1628		// Note: UpdateAnimeProgress already outputs a message on success
1629
1630		CurdOut("Series completed!")
1631		ExitCurd(nil)
1632		return
1633	}
1634
1635	// Increment episode number
1636	anime.Ep.Number++
1637
1638	// Check if we've reached the end of the series
1639	if anime.TotalEpisodes > 0 && anime.Ep.Number > anime.TotalEpisodes {
1640		CurdOut("Reached end of series")
1641		ExitCurd(nil)
1642		return
1643	}
1644
1645	// Use prefetched links if available for the next episode
1646	if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1647		anime.Ep.Links = anime.Ep.NextEpisode.Links
1648		Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number))
1649	} else {
1650		// Clear links to force fetching new ones
1651		anime.Ep.Links = []string{}
1652		Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
1653	}
1654
1655	// Reset episode flags
1656	anime.Ep.Started = false
1657	anime.Ep.IsCompleted = false
1658
1659	// Log the transition
1660	Log("Completed episode, starting next.")
1661
1662	// Update local database
1663	err := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, GetAnimeName(*anime))
1664	if err != nil {
1665		Log("Error updating local database: " + err.Error())
1666	}
1667
1668	go func() {
1669		err = UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1670		if err != nil {
1671			Log("Error updating Anilist progress: " + err.Error())
1672		}
1673	}()
1674
1675	// Output message to user
1676	CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
1677}
1678
1679// HandleLastEpisodeCompletion handles scoring and completion for the last episode
1680func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
1681	// Check if this is the last episode and scoring is enabled
1682	if userCurdConfig.ScoreOnCompletion && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !anime.IsAiring {
1683		// Prompt user to score the anime
1684		CurdOut("You've completed this anime! Would you like to rate it?")
1685
1686		scoreOptions := []SelectionOption{
1687			{Key: "yes", Label: "Yes, rate this anime"},
1688			{Key: "no", Label: "No, skip rating"},
1689		}
1690
1691		selectedOption, err := DynamicSelect(scoreOptions)
1692		if err != nil {
1693			Log(fmt.Sprintf("Error in score prompt selection: %v", err))
1694		} else if selectedOption.Key == "yes" {
1695			err = RateAnime(userToken, anime.AnilistId)
1696			if err != nil {
1697				Log(fmt.Sprintf("Error rating anime: %v", err))
1698				CurdOut("Failed to rate anime")
1699			} else {
1700				CurdOut("Anime rated successfully!")
1701			}
1702		}
1703		// Back (-2) and no are treated as skip
1704	}
1705
1706	// Update anime status to completed on AniList.
1707	// For rewatches, preserve the original completion date and only increment repeat count.
1708	if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !anime.IsAiring {
1709		if anime.Rewatching {
1710			err := CompleteAnimeRewatch(userToken, *anime)
1711			if err != nil {
1712				Log("Error completing anime rewatch: " + err.Error())
1713			}
1714		} else {
1715			err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED")
1716			if err != nil {
1717				Log("Error updating anime status to completed: " + err.Error())
1718			}
1719			// Note: UpdateAnimeStatus already outputs a message on success
1720		}
1721	}
1722
1723	// Check for sequel after completion (only if this is the last episode)
1724	if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1725		handleSequelCheck(userCurdConfig, anime, userToken)
1726	}
1727}
1728
1729// handleSequelCheck checks for sequels and prompts the user accordingly
1730func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
1731	// Recover from any panics in this function to prevent crashes
1732	defer func() {
1733		if r := recover(); r != nil {
1734			Log(fmt.Sprintf("Recovered from panic in handleSequelCheck: %v", r))
1735		}
1736	}()
1737
1738	// Fetch sequel information
1739	sequels, err := GetAnimeSequel(anime.AnilistId, userToken)
1740	if err != nil {
1741		Log(fmt.Sprintf("Error fetching sequel information: %v", err))
1742		return
1743	}
1744
1745	if len(sequels) == 0 {
1746		Log("No sequel found for this anime")
1747		return
1748	}
1749
1750	if len(sequels) > 1 {
1751		CurdOut("Multiple sequels found for this anime.")
1752		options := []SelectionOption{
1753			{Key: "yes", Label: "Open AniList page to view sequels"},
1754			{Key: "no", Label: "Ignore"},
1755		}
1756
1757		selectedOption, err := DynamicSelect(options)
1758		if err != nil {
1759			Log(fmt.Sprintf("Error in multiple sequel prompt: %v", err))
1760			return
1761		}
1762
1763		if selectedOption.Key == "yes" {
1764			url := fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId)
1765			CurdOut(fmt.Sprintf("Opening %s", url))
1766			if err := browser.OpenURL(url); err != nil {
1767				Log(fmt.Sprintf("Error opening browser: %v", err))
1768				CurdOut("Failed to open browser.")
1769			}
1770		}
1771		return
1772	}
1773
1774	sequel := &sequels[0]
1775
1776	// Get sequel title based on user's language preference
1777	sequelTitle := sequel.Title.Romaji
1778	if sequel.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
1779		sequelTitle = sequel.Title.English
1780	}
1781
1782	Log(fmt.Sprintf("Found sequel: %s (ID: %d)", sequelTitle, sequel.ID))
1783
1784	// Check if sequel is not yet released
1785	if sequel.Status == "NOT_YET_RELEASED" {
1786		CurdOut(fmt.Sprintf("A sequel '%s' is announced but not yet released.", sequelTitle))
1787		return
1788	}
1789
1790	// Fetch user's anime list to check if sequel is already there
1791	userId, _, err := GetAnilistUserID(userToken)
1792	if err != nil {
1793		Log(fmt.Sprintf("Error getting user ID: %v", err))
1794		return
1795	}
1796
1797	userData, err := GetUserData(userToken, userId)
1798	if err != nil {
1799		Log(fmt.Sprintf("Error getting user data: %v", err))
1800		return
1801	}
1802
1803	// Check if userData is valid before parsing
1804	if userData == nil || userData["data"] == nil {
1805		Log("User data is nil or malformed, skipping sequel list check")
1806		// Still show the sequel prompt, but assume it's not in any list
1807		promptSequelNotInList(sequel, sequelTitle, userToken, anime)
1808		return
1809	}
1810
1811	userAnimeList := ParseAnimeList(userData)
1812	sequelStatus, isInList := FindSequelInAnimeList(userAnimeList, sequel.ID)
1813
1814	if !isInList {
1815		// Sequel is not in any list - ask if user wants to add it
1816		CurdOut(fmt.Sprintf("A sequel is available: %s", sequelTitle))
1817
1818		options := []SelectionOption{
1819			{Key: "watching", Label: "Add to Watching list"},
1820			{Key: "planning", Label: "Add to Plan to Watch"},
1821			{Key: "skip", Label: "No thanks"},
1822		}
1823
1824		selectedOption, err := DynamicSelect(options)
1825		if err != nil {
1826			Log(fmt.Sprintf("Error in sequel prompt: %v", err))
1827			return
1828		}
1829
1830		switch selectedOption.Key {
1831		case "watching":
1832			err = AddAnimeToList(sequel.ID, "CURRENT", userToken)
1833			if err != nil {
1834				Log(fmt.Sprintf("Error adding sequel to watching list: %v", err))
1835				CurdOut("Failed to add sequel to watching list")
1836			} else {
1837				CurdOut(fmt.Sprintf("Added '%s' to your Watching list!", sequelTitle))
1838			}
1839		case "planning":
1840			err = AddAnimeToList(sequel.ID, "PLANNING", userToken)
1841			if err != nil {
1842				Log(fmt.Sprintf("Error adding sequel to planning list: %v", err))
1843				CurdOut("Failed to add sequel to Plan to Watch")
1844			} else {
1845				CurdOut(fmt.Sprintf("Added '%s' to your Plan to Watch list!", sequelTitle))
1846			}
1847		case "skip", "-1":
1848			Log("User declined to add sequel")
1849		}
1850	} else {
1851		// Sequel is already in a list
1852		switch sequelStatus {
1853		case "CURRENT":
1854			// Already in watching list
1855			CurdOut(fmt.Sprintf("The sequel '%s' is already in your Watching list!", sequelTitle))
1856
1857		case "PLANNING":
1858			// In planning list - ask if user wants to move to watching
1859			CurdOut(fmt.Sprintf("The sequel '%s' is in your Plan to Watch list. Move to Watching?", sequelTitle))
1860
1861			options := []SelectionOption{
1862				{Key: "yes", Label: "Yes, move to Watching list"},
1863				{Key: "no", Label: "No, keep in Plan to Watch"},
1864			}
1865
1866			selectedOption, err := DynamicSelect(options)
1867			if err != nil {
1868				Log(fmt.Sprintf("Error in sequel planning prompt: %v", err))
1869				return
1870			}
1871
1872			if selectedOption.Key == "yes" {
1873				err = AddAnimeToList(sequel.ID, "CURRENT", userToken)
1874				if err != nil {
1875					Log(fmt.Sprintf("Error moving sequel to watching list: %v", err))
1876					CurdOut("Failed to move sequel to Watching list")
1877				} else {
1878					CurdOut(fmt.Sprintf("Moved '%s' to Watching list!", sequelTitle))
1879				}
1880			}
1881
1882		case "COMPLETED":
1883			CurdOut(fmt.Sprintf("You've already completed the sequel '%s'!", sequelTitle))
1884
1885		case "PAUSED", "DROPPED":
1886			CurdOut(fmt.Sprintf("The sequel '%s' is in your %s list.", sequelTitle, sequelStatus))
1887
1888			options := []SelectionOption{
1889				{Key: "yes", Label: "Move to Watching list"},
1890				{Key: "no", Label: "No thanks"},
1891			}
1892
1893			selectedOption, err := DynamicSelect(options)
1894			if err != nil {
1895				Log(fmt.Sprintf("Error in sequel resume prompt: %v", err))
1896				return
1897			}
1898
1899			if selectedOption.Key == "yes" {
1900				err = AddAnimeToList(sequel.ID, "CURRENT", userToken)
1901				if err != nil {
1902					Log(fmt.Sprintf("Error moving sequel to watching list: %v", err))
1903					CurdOut("Failed to move sequel to Watching list")
1904				} else {
1905					CurdOut(fmt.Sprintf("Moved '%s' to Watching list!", sequelTitle))
1906				}
1907			}
1908		}
1909	}
1910}
1911
1912// promptSequelNotInList prompts user to add sequel when we can't check their list
1913func promptSequelNotInList(sequel *SequelInfo, sequelTitle string, userToken string, anime *Anime) {
1914	CurdOut(fmt.Sprintf("A sequel is available: %s", sequelTitle))
1915
1916	options := []SelectionOption{
1917		{Key: "watching", Label: "Add to Watching list"},
1918		{Key: "planning", Label: "Add to Plan to Watch"},
1919		{Key: "skip", Label: "No thanks"},
1920	}
1921
1922	selectedOption, err := DynamicSelect(options)
1923	if err != nil {
1924		Log(fmt.Sprintf("Error in sequel prompt: %v", err))
1925		return
1926	}
1927
1928	switch selectedOption.Key {
1929	case "watching":
1930		err = AddAnimeToList(sequel.ID, "CURRENT", userToken)
1931		if err != nil {
1932			Log(fmt.Sprintf("Error adding sequel to watching list: %v", err))
1933			CurdOut("Failed to add sequel to watching list")
1934		} else {
1935			CurdOut(fmt.Sprintf("Added '%s' to your Watching list!", sequelTitle))
1936		}
1937	case "planning":
1938		err = AddAnimeToList(sequel.ID, "PLANNING", userToken)
1939		if err != nil {
1940			Log(fmt.Sprintf("Error adding sequel to planning list: %v", err))
1941			CurdOut("Failed to add sequel to Plan to Watch")
1942		} else {
1943			CurdOut(fmt.Sprintf("Added '%s' to your Plan to Watch list!", sequelTitle))
1944		}
1945	case "skip", "-1":
1946		Log("User declined to add sequel")
1947	}
1948}