internal/curd.go

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