internal/curd.go

2339 lines · 76651 bytes

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