internal/curd.go

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