internal/curd.go

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