internal/curd.go

2258 lines · 73951 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						animeRef := parseAnimepaheProviderID(opt.Key)
1125						if animeRef.Session == "" {
1126							continue
1127						}
1128						animeUrl := fmt.Sprintf("https://animepahe.pw/anime/%s", animeRef.Session)
1129						Log(fmt.Sprintf("Fetching %s to check exact AniList meta tag...", animeUrl))
1130						req, _ := http.NewRequest("GET", animeUrl, nil)
1131						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")
1132
1133						resp, err := sharedHTTPClient.Do(req)
1134						if err == nil && resp.StatusCode == 200 {
1135							body, _ := io.ReadAll(resp.Body)
1136							resp.Body.Close()
1137							bodyStr := string(body)
1138
1139							metaTag := fmt.Sprintf(`<meta name="anilist" content="%s">`, targetAnilistID)
1140							if strings.Contains(bodyStr, metaTag) {
1141								Log(fmt.Sprintf("FOUND EXACT ANILIST META TAG MATCH in %s!", opt.Title))
1142								bestMatch = opt
1143								highestScore = 100 // Guarantee selection
1144								break
1145							} else {
1146								malMetaTag := fmt.Sprintf(`<meta name="mal" content="%d">`, anime.MalId)
1147								if anime.MalId != 0 && strings.Contains(bodyStr, malMetaTag) {
1148									Log(fmt.Sprintf("FOUND EXACT MAL META TAG MATCH in %s!", opt.Title))
1149									bestMatch = opt
1150									highestScore = 100
1151									break
1152								}
1153							}
1154						}
1155					}
1156
1157					if score > highestScore {
1158						highestScore = score
1159						bestMatch = opt
1160					}
1161				}
1162
1163				if bestMatch != nil && highestScore == 100 {
1164					anime.ProviderId = bestMatch.Key
1165					Log(fmt.Sprintf("Found EXACT meta tag match! Score: %d. Setting ProviderId to: %s", highestScore, anime.ProviderId))
1166					found = true
1167				} else if bestMatch != nil {
1168					Log(fmt.Sprintf("Highest match score was %d (needed 100 for Animepahe exact meta tag match). Not selecting automatically to prevent false positives.", highestScore))
1169				}
1170			}
1171
1172			// 3. Fallback to naive title/episode match
1173			if !found {
1174				targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes)
1175				for _, option := range animeList {
1176					if fmt.Sprintf("%s (%d episodes)", option.Title, selectedAnilistAnime.Media.Episodes) == targetLabel {
1177						anime.ProviderId = option.Key
1178						Log(fmt.Sprintf("Found exact text match! Setting ProviderId to: %s", anime.ProviderId))
1179						found = true
1180						break
1181					}
1182				}
1183				if !found {
1184					Log(fmt.Sprintf("No exact match found for label '%s'. Will require manual selection.", targetLabel))
1185				}
1186			}
1187
1188			// If unable to get Allanime id automatically get manually
1189			if anime.ProviderId == "" {
1190				CurdOut("We didn't find any matches. Please select manually.")
1191				selectedAllanimeAnime, err := DynamicSelect(animeList)
1192
1193				if selectedAllanimeAnime.Key == "-1" {
1194					ExitCurd(nil)
1195				}
1196
1197				// Handle back button - go back to main menu
1198				if selectedAllanimeAnime.Key == "-2" {
1199					CurdOut("Going back to main menu...")
1200					RestoreScreen()
1201					if anime.Ep.ContinueLast {
1202						anime.Ep.ContinueLast = false
1203					}
1204					continue
1205				}
1206
1207				if err != nil {
1208					ExitCurd(fmt.Errorf("No anime available"))
1209				}
1210				anime.ProviderId = selectedAllanimeAnime.Key
1211			}
1212		}
1213
1214		// if anime found in database, use its playback state
1215		if animePointer != nil {
1216			if !needsProviderSearch {
1217				anime.ProviderId = animePointer.ProviderId
1218			}
1219			anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
1220			if anime.Ep.Number == animePointer.Ep.Number {
1221				anime.Ep.Resume = true
1222			}
1223
1224			// If local history episode is ahead of AniList upstream, prompt user
1225			anilistEpisode := selectedAnilistAnime.Progress + 1
1226			if animePointer.Ep.Number > anilistEpisode {
1227				trackerLabel := RemoteTrackingDisplayName(userCurdConfig)
1228				Log(fmt.Sprintf("Local history episode (%d) is ahead of %s episode (%d), prompting user", animePointer.Ep.Number, trackerLabel, anilistEpisode))
1229				options := []SelectionOption{
1230					{Key: "update_upstream", Label: fmt.Sprintf("Update %s to episode %d (local history)", trackerLabel, animePointer.Ep.Number-1)},
1231					{Key: "use_anilist", Label: fmt.Sprintf("Use %s episode %d", trackerLabel, anilistEpisode)},
1232				}
1233				CurdOut(fmt.Sprintf("Local history (ep %d) is ahead of %s (ep %d).", animePointer.Ep.Number, trackerLabel, anilistEpisode))
1234				selectedOption, err := DynamicSelect(options)
1235				if err != nil {
1236					Log("Error in episode conflict selection: " + err.Error())
1237				} else if selectedOption.Key == "-1" {
1238					ExitCurd(nil)
1239				} else if selectedOption.Key == "update_upstream" {
1240					// Update remote progress to match local history (progress = local ep - 1, since local ep is "next to watch")
1241					progressToUpdate := animePointer.Ep.Number - 1
1242					if err := UpdateAnimeProgress(user.Token, anime.AnilistId, progressToUpdate); err != nil {
1243						Log(fmt.Sprintf("Error updating %s progress to %d: %v", trackerLabel, progressToUpdate, err))
1244					} else {
1245						Log(fmt.Sprintf("Updated %s progress to %d", trackerLabel, progressToUpdate))
1246					}
1247					anime.Ep.Number = animePointer.Ep.Number
1248					anime.Ep.Resume = true
1249				} else if selectedOption.Key == "use_anilist" {
1250					// Use remote episode number (already set from selectedAnilistAnime.Progress + 1)
1251					anime.Ep.Number = anilistEpisode
1252					anime.Ep.Player.PlaybackTime = 0
1253					anime.Ep.Resume = false
1254				}
1255			} else {
1256				anime.Ep.Number = animePointer.Ep.Number
1257			}
1258		}
1259
1260		if startingRewatch {
1261			anime.Ep.Player.PlaybackTime = 0
1262			anime.Ep.Resume = false
1263		}
1264
1265		if selectedAllanimeAnime.Key == "-1" {
1266			ExitCurd(nil)
1267		}
1268
1269		// If anime is not in watching list, prompt user to add it into watching list
1270		isInWatchingList := false
1271		for _, entry := range user.AnimeList.Watching {
1272			if entry.Media.ID == anime.AnilistId {
1273				isInWatchingList = true
1274				break
1275			}
1276		}
1277		if !isInWatchingList {
1278			for _, entry := range user.AnimeList.Rewatching {
1279				if entry.Media.ID == anime.AnilistId {
1280					isInWatchingList = true
1281					break
1282				}
1283			}
1284		}
1285		if anime.Rewatching {
1286			isInWatchingList = true
1287		}
1288
1289		if UsesRemoteTracking(userCurdConfig) && !isInWatchingList {
1290			// Create options for the prompt
1291			options := []SelectionOption{
1292				{Key: "yes", Label: "Add to watching list"},
1293				{Key: "no", Label: "Continue without adding"},
1294			}
1295
1296			var selectedOption SelectionOption
1297			var err error
1298
1299			// Use rofi for selection
1300			selectedOption, err = DynamicSelect(options)
1301			if err != nil {
1302				Log("Error in selection: " + err.Error())
1303				ExitCurd(err)
1304			}
1305
1306			if selectedOption.Key == "yes" {
1307				err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
1308				if err != nil {
1309					Log("Error adding anime to watching list: " + err.Error())
1310					ExitCurd(err)
1311				}
1312				if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
1313					Log("Error refreshing anime list: " + err.Error())
1314					ExitCurd(err)
1315				}
1316			} else if selectedOption.Key == "-1" {
1317				ExitCurd(nil)
1318			} else if selectedOption.Key == "-2" {
1319				// Handle back button - go back to main menu
1320				CurdOut("Going back to main menu...")
1321				RestoreScreen()
1322				// If we were continuing last, disable it so we go to menu next loop
1323				if anime.Ep.ContinueLast {
1324					anime.Ep.ContinueLast = false
1325				}
1326				continue
1327			}
1328		}
1329
1330		// If upstream is ahead, update the episode number
1331		if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
1332			if temp_anime.Progress > anime.Ep.Number {
1333				anime.Ep.Number = temp_anime.Progress
1334				anime.Ep.Player.PlaybackTime = 0
1335				anime.Ep.Resume = false
1336			}
1337		}
1338
1339		if anime.TotalEpisodes == 0 {
1340			// Get updated anime data
1341			Log(selectedAllanimeAnime)
1342			updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
1343			Log(updatedAnime)
1344			if err != nil {
1345				Log(fmt.Sprintf("Error getting updated anime data: %v", err))
1346			} else {
1347				anime.TotalEpisodes = updatedAnime.TotalEpisodes
1348				Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
1349			}
1350		}
1351
1352		if anime.TotalEpisodes == 0 { // If failed to get anime data
1353			CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
1354			animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
1355			if err != nil {
1356				CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
1357			} else {
1358				for _, option := range animeList {
1359					if option.Key == anime.ProviderId {
1360						// Extract total episodes from the label
1361						if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(option.Label); len(matches) > 1 {
1362							anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
1363							CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
1364							break
1365						}
1366					}
1367				}
1368			}
1369
1370			if anime.TotalEpisodes == 0 {
1371				CurdOut("Still unable to determine total episodes.")
1372				CurdOut(fmt.Sprintf("Your %s progress: %d", RemoteTrackingDisplayName(userCurdConfig), selectedAnilistAnime.Progress))
1373				var episodeNumber int
1374				if userCurdConfig.RofiSelection {
1375					userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
1376					if err != nil {
1377						Log("Error getting user input: " + err.Error())
1378						ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1379					}
1380					episodeNumber, err = strconv.Atoi(userInput)
1381				} else {
1382					fmt.Print("Enter the episode you want to start from: ")
1383					fmt.Scanln(&episodeNumber)
1384				}
1385				anime.Ep.Number = episodeNumber
1386			} else {
1387				anime.Ep.Number = selectedAnilistAnime.Progress + 1
1388			}
1389		} else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
1390			Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
1391			var answer string
1392			if userCurdConfig.RofiSelection {
1393				userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
1394				if err != nil {
1395					Log("Error getting user input: " + err.Error())
1396					ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1397				}
1398				answer = userInput
1399			} else {
1400				fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
1401				fmt.Scanln(&answer)
1402			}
1403			if answer == "y" {
1404				anime.Ep.Number = 1
1405			} else {
1406				anime.Ep.Number = anime.TotalEpisodes
1407			}
1408		}
1409
1410		// If we reached here successfully, break the loop
1411		break
1412	}
1413}
1414
1415// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
1416func WriteTokenToFile(token string, filePath string) error {
1417	// Extract the directory path
1418	dir := filepath.Dir(filePath)
1419
1420	// Create all necessary parent directories
1421	if err := os.MkdirAll(dir, 0755); err != nil {
1422		return fmt.Errorf("failed to create directories: %v", err)
1423	}
1424
1425	// Write the token to the file, creating it if it doesn't exist
1426	err := os.WriteFile(filePath, []byte(token), 0644)
1427	if err != nil {
1428		return fmt.Errorf("failed to write token to file: %v", err)
1429	}
1430
1431	return nil
1432}
1433
1434func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1435	if err := resolveRuntimeProviderID(userCurdConfig, anime); err != nil {
1436		Log(fmt.Sprintf("Failed to resolve provider id: %v", err))
1437		CurdOut("Failed to resolve anime provider id: " + err.Error())
1438		os.Exit(1)
1439	}
1440
1441	// Validate inputs
1442	if anime.ProviderId == "" {
1443		CurdOut("Error: No anime ID found")
1444		os.Exit(1)
1445	}
1446	if anime.Ep.Number <= 0 {
1447		CurdOut("Error: Invalid episode number")
1448		os.Exit(1)
1449	}
1450
1451	if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1452		anime.Ep.Links = anime.Ep.NextEpisode.Links
1453	} else {
1454		// Get episode link
1455		link, err := GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
1456		if len(link) > 0 {
1457			Log(fmt.Sprintf("Links details: %+v", link))
1458		}
1459		if err != nil {
1460			linkErr := err
1461			Log(fmt.Sprintf("GetEpisodeURL failed: %v", linkErr))
1462			if reselectProviderAnime(userCurdConfig, anime, linkErr) {
1463				link, err = GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
1464				if err == nil {
1465					Log(fmt.Sprintf("Successfully retrieved episode link after provider reselect. Links count: %d", len(link)))
1466					anime.Ep.Links = link
1467					goto episodeLinksReady
1468				}
1469				linkErr = err
1470				Log(fmt.Sprintf("GetEpisodeURL still failed after provider reselect: %v", linkErr))
1471			}
1472			// If unable to get episode link automatically get manually
1473			episodeList, listErr := EpisodesList(anime.ProviderId, userCurdConfig.SubOrDub)
1474			if listErr != nil {
1475				CurdOut("No episode list found: " + listErr.Error())
1476				Log(fmt.Sprintf("EpisodesList failed: %v", listErr))
1477				RestoreScreen()
1478				os.Exit(1)
1479			}
1480			if len(episodeList) == 0 {
1481				CurdOut("No episodes were returned by the current provider for this anime.")
1482				Log(fmt.Sprintf("EpisodesList returned no episodes for provider %s and id %s after GetEpisodeURL error: %v", GetProvider().Name(), anime.ProviderId, linkErr))
1483				RestoreScreen()
1484				os.Exit(1)
1485			}
1486			if userCurdConfig.RofiSelection {
1487				userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1488				if err != nil {
1489					Log("Error getting user input: " + err.Error())
1490					ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1491				}
1492				anime.Ep.Number, err = strconv.Atoi(userInput)
1493			} else {
1494				CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1495				fmt.Scanln(&anime.Ep.Number)
1496			}
1497			link, err = GetEpisodeURL(*userCurdConfig, anime.ProviderId, anime.Ep.Number)
1498			if err != nil {
1499				CurdOut("Failed to get episode link")
1500				os.Exit(1)
1501			}
1502		} else {
1503			Log(fmt.Sprintf("Successfully retrieved episode link on first try. Links count: %d", len(link)))
1504		}
1505		anime.Ep.Links = link
1506	}
1507
1508episodeLinksReady:
1509	if len(anime.Ep.Links) == 0 {
1510		CurdOut("No episode links found")
1511		os.Exit(1)
1512	} else {
1513		Log(fmt.Sprintf("Episode links validation passed. Found %d links", len(anime.Ep.Links)))
1514	}
1515
1516	// Modify the goroutine in main.go where next episode links are fetched
1517	// Get next episode link in parallel
1518	go func() {
1519		nextEpNum := anime.Ep.Number + 1
1520		if nextEpNum <= anime.TotalEpisodes {
1521			// Get next canon episode number if filler skip is enabled
1522			if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) {
1523				nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum)
1524			}
1525			nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.ProviderId, nextEpNum)
1526			if err != nil {
1527				Log(fmt.Sprintf("Error getting next episode link for ep %d: %v", nextEpNum, err))
1528			} else {
1529				anime.Ep.NextEpisode = NextEpisode{
1530					Number: nextEpNum,
1531					Links:  nextLinks,
1532				}
1533			}
1534		} else {
1535			Log(fmt.Sprintf("Next episode %d exceeds total episodes %d, skipping prefetch", nextEpNum, anime.TotalEpisodes))
1536		}
1537	}()
1538
1539	// Write anime.AnilistId to curd_id in the storage path
1540	idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1541	Log(fmt.Sprintf("idFilePath: %v", idFilePath))
1542	if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
1543		Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err))
1544	} else {
1545		if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
1546			Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err))
1547		}
1548	}
1549
1550	// Display starting message with cover image and episode info
1551	if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
1552		// Get the cached image path
1553		cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
1554		filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
1555		cachePath := filepath.Join(cacheDir, filename)
1556
1557		// Display the image if it exists in cache
1558		_, err := os.Stat(cachePath)
1559		if err == nil {
1560			// File exists
1561			Log(fmt.Sprintf("Image found at %s", cachePath))
1562			CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
1563		} else {
1564			// File does not exist
1565			Log(fmt.Sprintf("Image does not exist at %s", cachePath))
1566			CurdOut(fmt.Sprintf("%s - Episode %d",
1567				GetAnimeName(*anime),
1568				anime.Ep.Number))
1569
1570		}
1571	} else {
1572		CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
1573	}
1574	mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number), anime)
1575
1576	if err != nil {
1577		Log("Failed to start mpv")
1578		os.Exit(1)
1579	}
1580
1581	return mpvSocketPath
1582}
1583
1584func resolveRuntimeProviderID(userCurdConfig *CurdConfig, anime *Anime) error {
1585	if GetProvider().Name() != "animepahe" || anime == nil || anime.ProviderId == "" {
1586		return nil
1587	}
1588
1589	provider, ok := GetProvider().(*AnimepaheProvider)
1590	if !ok {
1591		return nil
1592	}
1593
1594	query := GetAnimeName(*anime)
1595	if query == "" {
1596		query = anime.Title.Romaji
1597	}
1598	if query == "" {
1599		query = anime.Title.English
1600	}
1601
1602	resolved, err := provider.ResolveProviderID(anime.ProviderId, query)
1603	if err != nil {
1604		return err
1605	}
1606	if resolved != "" && resolved != anime.ProviderId {
1607		Log(fmt.Sprintf("Resolved Animepahe provider id %s to runtime id %s", anime.ProviderId, resolved))
1608		anime.ProviderId = resolved
1609		anime.ProviderName = GetProvider().Name()
1610	}
1611
1612	return nil
1613}
1614
1615func reselectProviderAnime(userCurdConfig *CurdConfig, anime *Anime, reason error) bool {
1616	if GetProvider().Name() != "animepahe" {
1617		return false
1618	}
1619
1620	if reason != nil {
1621		Log(fmt.Sprintf("Attempting Animepahe provider reselect after error: %v", reason))
1622	}
1623
1624	query := GetAnimeName(*anime)
1625	if query == "" {
1626		query = anime.Title.Romaji
1627	}
1628	if query == "" {
1629		query = anime.Title.English
1630	}
1631	if query == "" {
1632		return false
1633	}
1634
1635	options, err := SearchAnime(query, userCurdConfig.SubOrDub)
1636	if err != nil {
1637		Log(fmt.Sprintf("Animepahe provider reselect search failed for %q: %v", query, err))
1638		return false
1639	}
1640	if len(options) == 0 {
1641		Log(fmt.Sprintf("Animepahe provider reselect found no results for %q", query))
1642		return false
1643	}
1644
1645	CurdOut("The saved Animepahe mapping is stale. Please select the anime again.")
1646	selected, err := DynamicSelect(options)
1647	if err != nil || selected.Key == "-1" || selected.Key == "-2" || selected.Key == "" {
1648		if err != nil {
1649			Log(fmt.Sprintf("Animepahe provider reselect failed: %v", err))
1650		}
1651		return false
1652	}
1653
1654	anime.ProviderId = selected.Key
1655	anime.ProviderName = GetProvider().Name()
1656	anime.Ep.NextEpisode = NextEpisode{}
1657	Log(fmt.Sprintf("Updated Animepahe ProviderId to %s after stale mapping", anime.ProviderId))
1658	return true
1659}
1660
1661func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1662	// Create storage directory if it doesn't exist
1663	storagePath = os.ExpandEnv(storagePath)
1664	if err := os.MkdirAll(storagePath, 0755); err != nil {
1665		return fmt.Errorf("failed to create storage directory: %v", err)
1666	}
1667
1668	// Base URL for downloading config files
1669	baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
1670
1671	// Check each file
1672	for _, fileName := range filesToCheck {
1673		filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
1674
1675		// Skip if file already exists
1676		if _, err := os.Stat(filePath); err == nil {
1677			continue
1678		}
1679
1680		// Download file if it doesn't exist
1681		resp, err := http.Get(baseURL + fileName)
1682		if err != nil {
1683			return fmt.Errorf("failed to download %s: %v", fileName, err)
1684		}
1685		defer resp.Body.Close()
1686
1687		// Create the file
1688		out, err := os.Create(filePath)
1689		if err != nil {
1690			return fmt.Errorf("failed to create file %s: %v", fileName, err)
1691		}
1692		defer out.Close()
1693
1694		// Write the content
1695		if _, err := io.Copy(out, resp.Body); err != nil {
1696			return fmt.Errorf("failed to write file %s: %v", fileName, err)
1697		}
1698	}
1699
1700	return nil
1701}
1702
1703func getEntriesByCategory(list AnimeList, category string) []Entry {
1704	switch category {
1705	case "ALL":
1706		// Combine all categories into one slice
1707		allEntries := make([]Entry, 0)
1708		allEntries = append(allEntries, list.Watching...)
1709		allEntries = append(allEntries, list.Completed...)
1710		allEntries = append(allEntries, list.Paused...)
1711		allEntries = append(allEntries, list.Dropped...)
1712		allEntries = append(allEntries, list.Planning...)
1713		allEntries = append(allEntries, list.Rewatching...)
1714		return allEntries
1715	case "CURRENT":
1716		currentEntries := make([]Entry, 0, len(list.Watching)+len(list.Rewatching))
1717		currentEntries = append(currentEntries, list.Watching...)
1718		currentEntries = append(currentEntries, list.Rewatching...)
1719		return currentEntries
1720	case "COMPLETED":
1721		return list.Completed
1722	case "PAUSED":
1723		return list.Paused
1724	case "DROPPED":
1725		return list.Dropped
1726	case "PLANNING":
1727		return list.Planning
1728	case "REWATCHING": // Added for completeness, though "ALL" covers it.
1729		return list.Rewatching
1730	default:
1731		return []Entry{}
1732	}
1733}
1734
1735func NextEpisodePromptCLI(userCurdConfig *CurdConfig) bool {
1736	anime := GetGlobalAnime()
1737
1738	// Show the next episode number that will be started
1739	nextEpisodeNum := anime.Ep.Number + 1
1740	CurdOut(fmt.Sprintf("Start next episode (%d)?", nextEpisodeNum))
1741
1742	// Create options for the selection - no "quit" option since it's built into selection menu
1743	options := []SelectionOption{
1744		{Key: "yes", Label: fmt.Sprintf("Yes, continue to episode %d", nextEpisodeNum)},
1745	}
1746
1747	// Use DynamicSelect for CLI mode
1748	selectedOption, err := DynamicSelect(options)
1749	if err != nil {
1750		Log(fmt.Sprintf("Error in CLI next episode prompt selection: %v", err))
1751		return false
1752	}
1753
1754	Log(fmt.Sprintf("CLI User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1755
1756	if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1757		// User selected to quit/back via the built-in option
1758		CurdOut("Exiting")
1759		return false
1760	}
1761
1762	return selectedOption.Key == "yes"
1763}
1764
1765// NextEpisodePromptContinuous provides a continuous next episode prompt for CLI mode
1766// This runs throughout the episode duration and handles completion logic
1767func NextEpisodePromptContinuous(userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1768	anime := GetGlobalAnime()
1769
1770	for {
1771		// Check if episode has started
1772		if !anime.Ep.Started {
1773			time.Sleep(1 * time.Second)
1774			continue
1775		}
1776
1777		// Show the next episode number that will be started
1778		nextEpisodeNum := anime.Ep.Number + 1
1779		CurdOut(fmt.Sprintf("Continue to next episode (%d) or quit?", nextEpisodeNum))
1780
1781		// Create options for the selection - no "quit" option since it's built into selection menu
1782		options := []SelectionOption{
1783			{Key: "yes", Label: "Yes, start next episode now"},
1784		}
1785
1786		// Use DynamicSelect for CLI mode
1787		selectedOption, err := DynamicSelect(options)
1788		if err != nil {
1789			Log(fmt.Sprintf("Error in CLI continuous next episode prompt: %v", err))
1790			break
1791		}
1792
1793		Log(fmt.Sprintf("CLI Continuous User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1794
1795		if selectedOption.Key == "-1" || selectedOption.Key == "-2" {
1796			// User selected to quit/back via the built-in option
1797
1798			// Check completion percentage
1799			percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
1800
1801			if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
1802				// Episode is considered completed, mark it and update progress
1803				anime.Ep.IsCompleted = true
1804
1805				// Handle completion if this was the last episode
1806				if anime.Ep.Number == anime.TotalEpisodes {
1807					HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
1808				}
1809
1810				// Update local database
1811				err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime), GetProvider().Name())
1812				if err != nil {
1813					Log("Error updating local database on quit: " + err.Error())
1814				}
1815
1816				if !(anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && anime.Rewatching) {
1817					go func() {
1818						err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number)
1819						if err != nil {
1820							Log("Error updating Anilist progress on quit: " + err.Error())
1821						}
1822					}()
1823				}
1824
1825				CurdOut(fmt.Sprintf("Episode completed (%.1f%% watched). Exiting.", percentageWatched))
1826			} else {
1827				CurdOut(fmt.Sprintf("Episode not completed (%.1f%% watched). Exiting.", percentageWatched))
1828			}
1829
1830			ExitMPV(anime.Ep.Player.SocketPath)
1831			ExitCurd(nil)
1832			return
1833		}
1834
1835		if selectedOption.Key == "yes" {
1836			// User wants to start next episode immediately
1837			anime.Ep.IsCompleted = true
1838
1839			// Update database with completed episode first
1840			err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, ConvertSecondsToMinutes(anime.Ep.Duration), GetAnimeName(*anime), GetProvider().Name())
1841			if err != nil {
1842				Log("Error updating local database with completed episode: " + err.Error())
1843			}
1844
1845			go func() {
1846				err = UpdateAnimeProgress(userToken, anime.AnilistId, anime.Ep.Number)
1847				if err != nil {
1848					Log("Error updating Anilist progress: " + err.Error())
1849				}
1850			}()
1851
1852			// Increment to next episode and update database with next episode number and 0 playback time
1853			anime.Ep.Number++
1854
1855			// Use prefetched links if available for the next episode
1856			if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1857				anime.Ep.Links = anime.Ep.NextEpisode.Links
1858				Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number))
1859			} else {
1860				// Clear links to force fetching new ones
1861				anime.Ep.Links = []string{}
1862				Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
1863			}
1864
1865			err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, GetAnimeName(*anime), GetProvider().Name())
1866			if err != nil {
1867				Log("Error updating local database with next episode: " + err.Error())
1868			}
1869
1870			CurdOut("Starting next episode now...")
1871			ExitMPV(anime.Ep.Player.SocketPath)
1872			return // Exit this function, let the main loop handle next episode
1873		}
1874	}
1875}
1876
1877// Simple next episode prompt for Rofi mode - just asks if user wants to continue
1878func NextEpisodePromptRofi(userCurdConfig *CurdConfig) bool {
1879	anime := GetGlobalAnime()
1880
1881	// Show the next episode number that will be started
1882	nextEpisodeNum := anime.Ep.Number + 1
1883
1884	// Create options for the selection
1885	options := []SelectionOption{
1886		{Key: "yes", Label: fmt.Sprintf("Yes, start episode %d", nextEpisodeNum)},
1887	}
1888
1889	// Use DynamicSelect for Rofi mode
1890	selectedOption, err := DynamicSelect(options)
1891	if err != nil {
1892		Log(fmt.Sprintf("Error in next episode prompt selection: %v", err))
1893		return false
1894	}
1895
1896	Log(fmt.Sprintf("Rofi User Selected Key: '%s', Label: '%s'", selectedOption.Key, selectedOption.Label))
1897
1898	return selectedOption.Key == "yes"
1899}
1900
1901// StartNextEpisode handles the logic for starting the next episode
1902// It updates the episode number, resets necessary flags, and handles database updates
1903func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile string, userToken string) {
1904	// Save previous episode number for progress update
1905	prevEpisode := anime.Ep.Number
1906
1907	// Check if we just completed the last episode
1908	if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
1909		// Handle scoring and completion for the last episode
1910		HandleLastEpisodeCompletion(userCurdConfig, anime, userToken)
1911
1912		if !anime.Rewatching {
1913			err := UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1914			if err != nil {
1915				Log("Error updating Anilist progress: " + err.Error())
1916			}
1917		}
1918		// Note: UpdateAnimeProgress already outputs a message on success
1919
1920		CurdOut("Series completed!")
1921		ExitCurd(nil)
1922		return
1923	}
1924
1925	// Increment episode number
1926	anime.Ep.Number++
1927
1928	// Check if we've reached the end of the series
1929	if anime.TotalEpisodes > 0 && anime.Ep.Number > anime.TotalEpisodes {
1930		CurdOut("Reached end of series")
1931		ExitCurd(nil)
1932		return
1933	}
1934
1935	// Use prefetched links if available for the next episode
1936	if (anime.Ep.NextEpisode.Number == anime.Ep.Number) && (len(anime.Ep.NextEpisode.Links) > 0) {
1937		anime.Ep.Links = anime.Ep.NextEpisode.Links
1938		Log(fmt.Sprintf("Using prefetched links for episode %d", anime.Ep.Number))
1939	} else {
1940		// Clear links to force fetching new ones
1941		anime.Ep.Links = []string{}
1942		Log(fmt.Sprintf("No prefetched links available for episode %d, will fetch new ones", anime.Ep.Number))
1943	}
1944
1945	// Reset episode flags
1946	anime.Ep.Started = false
1947	anime.Ep.IsCompleted = false
1948
1949	// Log the transition
1950	Log("Completed episode, starting next.")
1951
1952	// Update local database
1953	err := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, 0, 0, GetAnimeName(*anime), GetProvider().Name())
1954	if err != nil {
1955		Log("Error updating local database: " + err.Error())
1956	}
1957
1958	go func() {
1959		err = UpdateAnimeProgress(userToken, anime.AnilistId, prevEpisode)
1960		if err != nil {
1961			Log("Error updating Anilist progress: " + err.Error())
1962		}
1963	}()
1964
1965	// Output message to user
1966	CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
1967}
1968
1969// HandleLastEpisodeCompletion handles scoring and completion for the last episode
1970func HandleLastEpisodeCompletion(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
1971	// Check if this is the last episode and scoring is enabled
1972	if userCurdConfig.ScoreOnCompletion && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !anime.IsAiring {
1973		// Prompt user to score the anime
1974		CurdOut("You've completed this anime! Would you like to rate it?")
1975
1976		scoreOptions := []SelectionOption{
1977			{Key: "yes", Label: "Yes, rate this anime"},
1978			{Key: "no", Label: "No, skip rating"},
1979		}
1980
1981		selectedOption, err := DynamicSelect(scoreOptions)
1982		if err != nil {
1983			Log(fmt.Sprintf("Error in score prompt selection: %v", err))
1984		} else if selectedOption.Key == "yes" {
1985			err = RateAnime(userToken, anime.AnilistId)
1986			if err != nil {
1987				Log(fmt.Sprintf("Error rating anime: %v", err))
1988				CurdOut("Failed to rate anime")
1989			} else {
1990				CurdOut("Anime rated successfully!")
1991			}
1992		}
1993		// Back (-2) and no are treated as skip
1994	}
1995
1996	// Update anime status to completed on AniList.
1997	// For rewatches, preserve the original completion date and only increment repeat count.
1998	if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !anime.IsAiring {
1999		if anime.Rewatching {
2000			err := CompleteAnimeRewatch(userToken, *anime)
2001			if err != nil {
2002				Log("Error completing anime rewatch: " + err.Error())
2003			}
2004		} else {
2005			err := UpdateAnimeStatus(userToken, anime.AnilistId, "COMPLETED")
2006			if err != nil {
2007				Log("Error updating anime status to completed: " + err.Error())
2008			}
2009			// Note: UpdateAnimeStatus already outputs a message on success
2010		}
2011	}
2012
2013	// Check for sequel after completion (only if this is the last episode)
2014	if anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes {
2015		handleSequelCheck(userCurdConfig, anime, userToken)
2016	}
2017}
2018
2019// handleSequelCheck checks for sequels and prompts the user accordingly
2020func handleSequelCheck(userCurdConfig *CurdConfig, anime *Anime, userToken string) {
2021	if !UsesRemoteTracking(userCurdConfig) {
2022		return
2023	}
2024
2025	// Recover from any panics in this function to prevent crashes
2026	defer func() {
2027		if r := recover(); r != nil {
2028			Log(fmt.Sprintf("Recovered from panic in handleSequelCheck: %v", r))
2029		}
2030	}()
2031
2032	// Fetch sequel information
2033	sequels, err := GetAnimeSequel(anime.AnilistId, userToken)
2034	if err != nil {
2035		Log(fmt.Sprintf("Error fetching sequel information: %v", err))
2036		return
2037	}
2038
2039	if len(sequels) == 0 {
2040		Log("No sequel found for this anime")
2041		return
2042	}
2043
2044	if len(sequels) > 1 {
2045		CurdOut("Multiple sequels found for this anime.")
2046		options := []SelectionOption{
2047			{Key: "yes", Label: "Open AniList page to view sequels"},
2048			{Key: "no", Label: "Ignore"},
2049		}
2050
2051		selectedOption, err := DynamicSelect(options)
2052		if err != nil {
2053			Log(fmt.Sprintf("Error in multiple sequel prompt: %v", err))
2054			return
2055		}
2056
2057		if selectedOption.Key == "yes" {
2058			url := fmt.Sprintf("https://anilist.co/anime/%d", anime.AnilistId)
2059			CurdOut(fmt.Sprintf("Opening %s", url))
2060			if err := browser.OpenURL(url); err != nil {
2061				Log(fmt.Sprintf("Error opening browser: %v", err))
2062				CurdOut("Failed to open browser.")
2063			}
2064		}
2065		return
2066	}
2067
2068	sequel := &sequels[0]
2069
2070	// Get sequel title based on user's language preference
2071	sequelTitle := sequel.Title.Romaji
2072	if sequel.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
2073		sequelTitle = sequel.Title.English
2074	}
2075
2076	Log(fmt.Sprintf("Found sequel: %s (ID: %d)", sequelTitle, sequel.ID))
2077
2078	// Check if sequel is not yet released
2079	if sequel.Status == "NOT_YET_RELEASED" {
2080		CurdOut(fmt.Sprintf("A sequel '%s' is announced but not yet released.", sequelTitle))
2081		return
2082	}
2083
2084	currentUser := GetGlobalUser()
2085	userAnimeList := AnimeList{}
2086	if currentUser != nil {
2087		userAnimeList = currentUser.AnimeList
2088	}
2089	if !hasAnyEntries(userAnimeList) {
2090		Log("Tracked anime list is empty, skipping sequel list check")
2091		promptSequelNotInList(sequel, sequelTitle, userToken, anime)
2092		return
2093	}
2094	sequelStatus, isInList := FindSequelInAnimeList(userAnimeList, sequel.ID)
2095
2096	if !isInList {
2097		// Sequel is not in any list - ask if user wants to add it
2098		CurdOut(fmt.Sprintf("A sequel is available: %s", sequelTitle))
2099
2100		options := []SelectionOption{
2101			{Key: "watching", Label: "Add to Watching list"},
2102			{Key: "planning", Label: "Add to Plan to Watch"},
2103			{Key: "skip", Label: "No thanks"},
2104		}
2105
2106		selectedOption, err := DynamicSelect(options)
2107		if err != nil {
2108			Log(fmt.Sprintf("Error in sequel prompt: %v", err))
2109			return
2110		}
2111
2112		switch selectedOption.Key {
2113		case "watching":
2114			err = AddAnimeToList(sequel.ID, "CURRENT", userToken)
2115			if err != nil {
2116				Log(fmt.Sprintf("Error adding sequel to watching list: %v", err))
2117				CurdOut("Failed to add sequel to watching list")
2118			} else {
2119				CurdOut(fmt.Sprintf("Added '%s' to your Watching list!", sequelTitle))
2120			}
2121		case "planning":
2122			err = AddAnimeToList(sequel.ID, "PLANNING", userToken)
2123			if err != nil {
2124				Log(fmt.Sprintf("Error adding sequel to planning list: %v", err))
2125				CurdOut("Failed to add sequel to Plan to Watch")
2126			} else {
2127				CurdOut(fmt.Sprintf("Added '%s' to your Plan to Watch list!", sequelTitle))
2128			}
2129		case "skip", "-1":
2130			Log("User declined to add sequel")
2131		}
2132	} else {
2133		// Sequel is already in a list
2134		switch sequelStatus {
2135		case "CURRENT":
2136			// Already in watching list
2137			CurdOut(fmt.Sprintf("The sequel '%s' is already in your Watching list!", sequelTitle))
2138
2139		case "PLANNING":
2140			// In planning list - ask if user wants to move to watching
2141			CurdOut(fmt.Sprintf("The sequel '%s' is in your Plan to Watch list. Move to Watching?", sequelTitle))
2142
2143			options := []SelectionOption{
2144				{Key: "yes", Label: "Yes, move to Watching list"},
2145				{Key: "no", Label: "No, keep in Plan to Watch"},
2146			}
2147
2148			selectedOption, err := DynamicSelect(options)
2149			if err != nil {
2150				Log(fmt.Sprintf("Error in sequel planning prompt: %v", err))
2151				return
2152			}
2153
2154			if selectedOption.Key == "yes" {
2155				err = AddAnimeToList(sequel.ID, "CURRENT", userToken)
2156				if err != nil {
2157					Log(fmt.Sprintf("Error moving sequel to watching list: %v", err))
2158					CurdOut("Failed to move sequel to Watching list")
2159				} else {
2160					CurdOut(fmt.Sprintf("Moved '%s' to Watching list!", sequelTitle))
2161				}
2162			}
2163
2164		case "COMPLETED":
2165			CurdOut(fmt.Sprintf("You've already completed the sequel '%s'!", sequelTitle))
2166
2167		case "PAUSED", "DROPPED":
2168			CurdOut(fmt.Sprintf("The sequel '%s' is in your %s list.", sequelTitle, sequelStatus))
2169
2170			options := []SelectionOption{
2171				{Key: "yes", Label: "Move to Watching list"},
2172				{Key: "no", Label: "No thanks"},
2173			}
2174
2175			selectedOption, err := DynamicSelect(options)
2176			if err != nil {
2177				Log(fmt.Sprintf("Error in sequel resume prompt: %v", err))
2178				return
2179			}
2180
2181			if selectedOption.Key == "yes" {
2182				err = AddAnimeToList(sequel.ID, "CURRENT", userToken)
2183				if err != nil {
2184					Log(fmt.Sprintf("Error moving sequel to watching list: %v", err))
2185					CurdOut("Failed to move sequel to Watching list")
2186				} else {
2187					CurdOut(fmt.Sprintf("Moved '%s' to Watching list!", sequelTitle))
2188				}
2189			}
2190		}
2191	}
2192}
2193
2194// promptSequelNotInList prompts user to add sequel when we can't check their list
2195func promptSequelNotInList(sequel *SequelInfo, sequelTitle string, userToken string, anime *Anime) {
2196	CurdOut(fmt.Sprintf("A sequel is available: %s", sequelTitle))
2197
2198	options := []SelectionOption{
2199		{Key: "watching", Label: "Add to Watching list"},
2200		{Key: "planning", Label: "Add to Plan to Watch"},
2201		{Key: "skip", Label: "No thanks"},
2202	}
2203
2204	selectedOption, err := DynamicSelect(options)
2205	if err != nil {
2206		Log(fmt.Sprintf("Error in sequel prompt: %v", err))
2207		return
2208	}
2209
2210	switch selectedOption.Key {
2211	case "watching":
2212		err = AddAnimeToList(sequel.ID, "CURRENT", userToken)
2213		if err != nil {
2214			Log(fmt.Sprintf("Error adding sequel to watching list: %v", err))
2215			CurdOut("Failed to add sequel to watching list")
2216		} else {
2217			CurdOut(fmt.Sprintf("Added '%s' to your Watching list!", sequelTitle))
2218		}
2219	case "planning":
2220		err = AddAnimeToList(sequel.ID, "PLANNING", userToken)
2221		if err != nil {
2222			Log(fmt.Sprintf("Error adding sequel to planning list: %v", err))
2223			CurdOut("Failed to add sequel to Plan to Watch")
2224		} else {
2225			CurdOut(fmt.Sprintf("Added '%s' to your Plan to Watch list!", sequelTitle))
2226		}
2227	case "skip", "-1":
2228		Log("User declined to add sequel")
2229	}
2230}
2231
2232// ChangeProvider allows the user to switch the anime provider
2233func ChangeProvider(userCurdConfig *CurdConfig) {
2234	options := []SelectionOption{
2235		{Key: "allanime", Label: "allanime"},
2236		{Key: "animepahe", Label: "animepahe"},
2237	}
2238
2239	selected, err := DynamicSelect(options)
2240	if err != nil || selected.Key == "-1" || selected.Key == "-2" {
2241		return
2242	}
2243
2244	// Update the config
2245	userCurdConfig.Provider = selected.Key
2246	CurrentProvider = nil // reset the provider instance
2247
2248	// Save to config file
2249	configPath := GlobalConfigPath
2250	configMap, err := LoadConfigFromFile(configPath)
2251	if err == nil {
2252		configMap["Provider"] = selected.Key
2253		SaveConfigToFile(configPath, configMap)
2254	}
2255
2256	CurdOut(fmt.Sprintf("\nProvider successfully changed to %s.\n", selected.Label))
2257	time.Sleep(1 * time.Second)
2258}