internal/curd.go

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