internal/curd.go

1434 lines · 44667 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	"bufio"
  18	"github.com/gen2brain/beeep"
  19)
  20
  21func GetTokenFromFile(filePath string) (string, error) {
  22	// Read the token from the file
  23	data, err := os.ReadFile(filePath)
  24	if err != nil {
  25		return "", fmt.Errorf("failed to read token from file: %w", err)
  26	}
  27
  28	// Convert the byte slice to a string and remove any surrounding whitespace or newlines
  29	token := strings.TrimSpace(string(data))
  30
  31	return token, nil
  32}
  33
  34func EditConfig(configFilePath string) {
  35	// Get the user's preferred editor from the EDITOR environment variable
  36	editor := os.Getenv("EDITOR")
  37	if editor == "" {
  38		// If EDITOR is not set, use system-specific defaults
  39		if runtime.GOOS == "windows" {
  40			// Try Notepad++ first
  41			if _, err := exec.LookPath("notepad++"); err == nil {
  42				editor = "notepad++"
  43			} else {
  44				editor = "notepad.exe"
  45			}
  46		} else {
  47			if _, err := exec.LookPath("vim"); err == nil {
  48				editor = "vim"
  49			} else {
  50				editor = "nano"
  51			}
  52		}
  53	}
  54
  55	// Construct the command to open the config file
  56	cmd := exec.Command(editor, configFilePath)
  57
  58	// Set the command to run in the current terminal
  59	cmd.Stdin = os.Stdin
  60	cmd.Stdout = os.Stdout
  61	cmd.Stderr = os.Stderr
  62
  63	// Run the editor command
  64	err := cmd.Run()
  65	if err != nil {
  66		CurdOut(fmt.Sprintf("Error opening config file: %v", err))
  67		return
  68	}
  69
  70	CurdOut("Config file edited successfully.")
  71}
  72
  73// ClearLogFile removes all contents from the specified log file
  74func ClearLogFile(logFile string) error {
  75	// Open the file with truncate flag to clear its contents
  76	file, err := os.OpenFile(logFile, os.O_WRONLY|os.O_TRUNC, 0666)
  77	if err != nil {
  78		return fmt.Errorf("failed to open log file: %w", err)
  79	}
  80	defer file.Close()
  81
  82	return nil
  83}
  84
  85// LogData logs the input data into a specified log file with the format [LOG] time lineNumber: logData
  86func Log(data interface{}) error {
  87	logFile := GetGlobalLogFile()
  88	// Open or create the log file
  89	file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
  90	if err != nil {
  91		return err
  92	}
  93	defer file.Close()
  94
  95	// Attempt to marshal the data into JSON
  96	jsonData, err := json.Marshal(data)
  97	if err != nil {
  98		return err
  99	}
 100
 101	// Get the caller information
 102	_, filename, lineNumber, ok := runtime.Caller(1) // Caller 1 gives the caller of LogData
 103	if !ok {
 104		return fmt.Errorf("unable to get caller information")
 105	}
 106
 107	// Log the current time and the JSON representation along with caller info
 108	currentTime := time.Now().Format("2006/01/02 15:04:05")
 109	logMessage := fmt.Sprintf("[LOG] %s %s:%d: %s\n", currentTime, filename, lineNumber, jsonData)
 110	_, err = fmt.Fprint(file, logMessage) // Write to the file
 111	if err != nil {
 112		return err
 113	}
 114
 115	return nil
 116}
 117
 118// ClearScreen clears the terminal screen and saves the state
 119func ClearScreen() {
 120	userCurdConfig := GetGlobalConfig()
 121
 122	if userCurdConfig.AlternateScreen == false {
 123		return
 124	}
 125
 126	fmt.Print("\033[?1049h") // Switch to alternate screen buffer
 127	fmt.Print("\033[2J")     // Clear the entire screen
 128	fmt.Print("\033[H")      // Move cursor to the top left
 129}
 130
 131// RestoreScreen restores the original terminal state
 132func RestoreScreen() {
 133	userCurdConfig := GetGlobalConfig()
 134
 135	if userCurdConfig.AlternateScreen == false {
 136		return
 137	}
 138
 139	fmt.Print("\033[?1049l") // Switch back to the main screen buffer
 140}
 141
 142func ExitCurd(err error) {
 143	RestoreScreen()
 144
 145	anime := GetGlobalAnime()
 146	if anime != nil && anime.Ep.Player.SocketPath != "" {
 147		_, err = MPVSendCommand(anime.Ep.Player.SocketPath, []interface{}{"quit"})
 148		if err != nil {
 149			Log("Error closing MPV: " + err.Error())
 150		}
 151	}
 152
 153	CurdOut("Have a great day!")
 154	// If the error is not about the connection refused, print the error
 155	if err != nil && !strings.Contains(err.Error(), "dial unix "+anime.Ep.Player.SocketPath+": connect: connection refused") {
 156		CurdOut(fmt.Sprintf("Error: %v", err))
 157		if runtime.GOOS == "windows" {
 158			fmt.Println("Press Enter to exit")
 159			var wait string
 160			fmt.Scanln(&wait)
 161			os.Exit(1)
 162		} else {
 163			os.Exit(1)
 164		}
 165	}
 166	os.Exit(0)
 167}
 168
 169func CurdOut(data interface{}) {
 170	userCurdConfig := GetGlobalConfig()
 171	if userCurdConfig == nil {
 172		userCurdConfig = &CurdConfig{}
 173	}
 174	if !userCurdConfig.RofiSelection {
 175		fmt.Println(fmt.Sprintf("%v", data))
 176	} else {
 177		switch runtime.GOOS {
 178		case "windows":
 179			err := beeep.Notify(
 180				"Curd",
 181				fmt.Sprintf("%v", data),
 182				"",
 183			)
 184
 185			if err != nil {
 186				Log(fmt.Sprintf("Failed to send notification: %v", err))
 187			}
 188		case "linux":
 189			// Check if the input starts with "-i" for image notification
 190			dataStr := fmt.Sprintf("%v", data)
 191			if strings.HasPrefix(dataStr, "-i") && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
 192				// Split the string to get image path and message
 193				parts := strings.SplitN(dataStr, " ", 3)
 194				if len(parts) == 3 {
 195					// Remove quotes from the message
 196					message := strings.Trim(parts[2], "\"")
 197					cmd := exec.Command("notify-send",
 198						"-a", "Curd",
 199						"-h", "string:x-canonical-private-synchronous:curd-notification",
 200						"Curd",
 201						"-i", parts[1],
 202						message)
 203					err := cmd.Run()
 204					if err != nil {
 205						Log(fmt.Sprintf("%v", cmd))
 206						Log(fmt.Sprintf("Failed to send notification: %v", err))
 207					}
 208				}
 209			} else {
 210				cmd := exec.Command("notify-send",
 211					"-a", "Curd",
 212					"-h", "string:x-canonical-private-synchronous:curd-notification",
 213					"Curd",
 214					dataStr)
 215				err := cmd.Run()
 216				if err != nil {
 217					Log(fmt.Sprintf("%v", cmd))
 218					Log(fmt.Sprintf("Failed to send notification: %v", err))
 219				}
 220			}
 221		}
 222	}
 223}
 224
 225func UpdateAnimeEntry(userCurdConfig *CurdConfig, user *User) {
 226	// Create update options map
 227	updateOptions := map[string]string{
 228		"CATEGORY": "Change Anime Category",
 229		"PROGRESS": "Change Progress",
 230		"SCORE":    "Add/Change Score",
 231	}
 232
 233	// Select update option
 234	updateSelection, err := DynamicSelect(updateOptions)
 235	if err != nil {
 236		Log(fmt.Sprintf("Failed to select update option: %v", err))
 237		ExitCurd(fmt.Errorf("Failed to select update option"))
 238	}
 239
 240	if updateSelection.Key == "-1" {
 241		ExitCurd(nil)
 242	}
 243
 244	// Get user's anime list
 245	var animeListMap map[string]string
 246	var animeListMapPreview map[string]RofiSelectPreview
 247
 248	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 249		animeListMapPreview = make(map[string]RofiSelectPreview)
 250		// Include anime from all categories
 251		for _, entry := range user.AnimeList.Watching {
 252			title := entry.Media.Title.English
 253			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 254				title = entry.Media.Title.Romaji
 255			}
 256			animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 257				Title:      title,
 258				CoverImage: entry.CoverImage,
 259			}
 260		}
 261		for _, entry := range user.AnimeList.Completed {
 262			title := entry.Media.Title.English
 263			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 264				title = entry.Media.Title.Romaji
 265			}
 266			animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 267				Title:      title,
 268				CoverImage: entry.CoverImage,
 269			}
 270		}
 271		for _, entry := range user.AnimeList.Paused {
 272			title := entry.Media.Title.English
 273			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 274				title = entry.Media.Title.Romaji
 275			}
 276			animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 277				Title:      title,
 278				CoverImage: entry.CoverImage,
 279			}
 280		}
 281		for _, entry := range user.AnimeList.Dropped {
 282			title := entry.Media.Title.English
 283			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 284				title = entry.Media.Title.Romaji
 285			}
 286			animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 287				Title:      title,
 288				CoverImage: entry.CoverImage,
 289			}
 290		}
 291		for _, entry := range user.AnimeList.Planning {
 292			title := entry.Media.Title.English
 293			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 294				title = entry.Media.Title.Romaji
 295			}
 296			animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 297				Title:      title,
 298				CoverImage: entry.CoverImage,
 299			}
 300		}
 301	} else {
 302		animeListMap = make(map[string]string)
 303		// Include anime from all categories
 304		for _, entry := range user.AnimeList.Watching {
 305			title := entry.Media.Title.English
 306			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 307				title = entry.Media.Title.Romaji
 308			}
 309			animeListMap[strconv.Itoa(entry.Media.ID)] = title
 310		}
 311		for _, entry := range user.AnimeList.Completed {
 312			title := entry.Media.Title.English
 313			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 314				title = entry.Media.Title.Romaji
 315			}
 316			animeListMap[strconv.Itoa(entry.Media.ID)] = title
 317		}
 318		for _, entry := range user.AnimeList.Paused {
 319			title := entry.Media.Title.English
 320			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 321				title = entry.Media.Title.Romaji
 322			}
 323			animeListMap[strconv.Itoa(entry.Media.ID)] = title
 324		}
 325		for _, entry := range user.AnimeList.Dropped {
 326			title := entry.Media.Title.English
 327			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 328				title = entry.Media.Title.Romaji
 329			}
 330			animeListMap[strconv.Itoa(entry.Media.ID)] = title
 331		}
 332		for _, entry := range user.AnimeList.Planning {
 333			title := entry.Media.Title.English
 334			if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 335				title = entry.Media.Title.Romaji
 336			}
 337			animeListMap[strconv.Itoa(entry.Media.ID)] = title
 338		}
 339	}
 340
 341	// Select anime to update
 342	var selectedAnime SelectionOption
 343	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 344		selectedAnime, err = DynamicSelectPreview(animeListMapPreview, false)
 345	} else {
 346		selectedAnime, err = DynamicSelect(animeListMap)
 347	}
 348	if err != nil {
 349		Log(fmt.Sprintf("Failed to select anime: %v", err))
 350		ExitCurd(fmt.Errorf("Failed to select anime"))
 351	}
 352
 353	if selectedAnime.Key == "-1" {
 354		ExitCurd(nil)
 355	}
 356
 357	animeID, err := strconv.Atoi(selectedAnime.Key)
 358	if err != nil {
 359		Log(fmt.Sprintf("Failed to convert anime ID: %v", err))
 360		ExitCurd(fmt.Errorf("Failed to convert anime ID"))
 361	}
 362
 363	// After getting animeID, get the current anime entry
 364	selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, selectedAnime.Key)
 365	if err != nil {
 366		Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err))
 367		ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
 368	}
 369	ClearScreen()
 370	switch updateSelection.Key {
 371	case "CATEGORY":
 372		categories := map[string]string{
 373			"CURRENT":   "Currently Watching",
 374			"COMPLETED": "Completed",
 375			"PAUSED":    "On Hold",
 376			"DROPPED":   "Dropped",
 377			"PLANNING":  "Plan to Watch",
 378		}
 379
 380		currentStatus := "None"
 381		if selectedAnilistAnime.Status != "" {
 382			currentStatus = categories[selectedAnilistAnime.Status]
 383		}
 384		CurdOut(fmt.Sprintf("Current category: %s", currentStatus))
 385
 386		categorySelection, err := DynamicSelect(categories)
 387		if err != nil {
 388			Log(fmt.Sprintf("Failed to select category: %v", err))
 389			ExitCurd(fmt.Errorf("Failed to select category"))
 390		}
 391
 392		if categorySelection.Key == "-1" {
 393			ExitCurd(nil)
 394		}
 395
 396		err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
 397		if err != nil {
 398			Log(fmt.Sprintf("Failed to update anime status: %v", err))
 399			ExitCurd(fmt.Errorf("Failed to update anime status"))
 400		}
 401
 402	case "PROGRESS":
 403		currentProgress := "None"
 404		if selectedAnilistAnime.Progress > 0 {
 405			currentProgress = strconv.Itoa(selectedAnilistAnime.Progress)
 406		}
 407
 408		var progress string
 409		if userCurdConfig.RofiSelection {
 410			progress, err = GetUserInputFromRofi(fmt.Sprintf("Current progress: %s\nEnter new progress (episode number)", currentProgress))
 411			if err != nil {
 412				Log(fmt.Sprintf("Failed to get progress input: %v", err))
 413				ExitCurd(fmt.Errorf("Failed to get progress input"))
 414			}
 415		} else {
 416			CurdOut(fmt.Sprintf("Current progress: %s", currentProgress))
 417			CurdOut("Enter new progress (episode number):")
 418			fmt.Scanln(&progress)
 419		}
 420
 421		progressNum, err := strconv.Atoi(progress)
 422		if err != nil {
 423			Log(fmt.Sprintf("Failed to convert progress to number: %v", err))
 424			ExitCurd(fmt.Errorf("Failed to convert progress to number"))
 425		}
 426
 427		err = UpdateAnimeProgress(user.Token, animeID, progressNum)
 428		if err != nil {
 429			Log(fmt.Sprintf("Failed to update anime progress: %v", err))
 430			ExitCurd(fmt.Errorf("Failed to update anime progress"))
 431		}
 432
 433	case "SCORE":
 434		currentScore := "None"
 435		if selectedAnilistAnime.Score > 0 {
 436			currentScore = strconv.Itoa(int(selectedAnilistAnime.Score))
 437		}
 438		CurdOut(fmt.Sprintf("Current score: %s", currentScore))
 439
 440		err = RateAnime(user.Token, animeID)
 441		if err != nil {
 442			Log(fmt.Sprintf("Failed to update anime score: %v", err))
 443			ExitCurd(fmt.Errorf("Failed to update anime score"))
 444		}
 445	}
 446
 447	CurdOut("Anime updated successfully!")
 448}
 449
 450func UpdateCurd(repo, fileName string) error {
 451	// Get the path of the currently running executable
 452	executablePath, err := os.Executable()
 453	if err != nil {
 454		return fmt.Errorf("unable to find current executable: %v", err)
 455	}
 456
 457	// Determine the correct binary name based on OS and architecture
 458	var binaryName string
 459	switch runtime.GOOS {
 460	case "windows":
 461		if runtime.GOARCH == "arm64" {
 462			binaryName = "curd-windows-arm64.exe"
 463		} else {
 464			binaryName = "curd-windows-x86_64.exe"
 465		}
 466	case "darwin": // macOS
 467		switch runtime.GOARCH {
 468		case "amd64":
 469			binaryName = "curd-macos-x86_64"
 470		case "arm64":
 471			binaryName = "curd-macos-arm64"
 472		default:
 473			binaryName = "curd-macos-universal"
 474		}
 475	case "linux":
 476		switch runtime.GOARCH {
 477		case "amd64":
 478			binaryName = "curd-linux-x86_64"
 479		case "arm64":
 480			binaryName = "curd-linux-arm64"
 481		default:
 482			return fmt.Errorf("unsupported Linux architecture: %s", runtime.GOARCH)
 483		}
 484	default:
 485		return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
 486	}
 487
 488	// GitHub release URL for curd
 489	url := fmt.Sprintf("https://github.com/%s/releases/latest/download/%s", repo, binaryName)
 490
 491	// Temporary path for the downloaded curd executable
 492	tmpPath := executablePath + ".tmp"
 493
 494	// Download the curd executable
 495	resp, err := http.Get(url)
 496	if err != nil {
 497		return fmt.Errorf("failed to download file: %v", err)
 498	}
 499	defer resp.Body.Close()
 500
 501	// Check if the download was successful
 502	if resp.StatusCode != http.StatusOK {
 503		return fmt.Errorf("failed to download file: received status code %d", resp.StatusCode)
 504	}
 505
 506	// Create a new temporary file
 507	out, err := os.Create(tmpPath)
 508	if err != nil {
 509		return fmt.Errorf("failed to create temporary file: %v", err)
 510	}
 511	defer out.Close()
 512
 513	// Set file permissions
 514	if err := out.Chmod(0755); err != nil {
 515		return fmt.Errorf("failed to set file permissions: %v", err)
 516	}
 517
 518	// Copy the downloaded content to the temporary file
 519	if _, err := io.Copy(out, resp.Body); err != nil {
 520		return fmt.Errorf("failed to write to temporary file: %v", err)
 521	}
 522
 523	// Close the file before renaming
 524	out.Close()
 525
 526	// Replace the old executable with the new one
 527	if runtime.GOOS == "windows" {
 528		// On Windows, we need to rename the old file first
 529		oldPath := executablePath + ".old"
 530		err = os.Rename(executablePath, oldPath)
 531		if err != nil {
 532			return fmt.Errorf("failed to rename old executable: %v", err)
 533		}
 534		err = os.Rename(tmpPath, executablePath)
 535		if err != nil {
 536			// Try to restore the old executable if the rename fails
 537			os.Rename(oldPath, executablePath)
 538			return fmt.Errorf("failed to rename new executable: %v", err)
 539		}
 540		os.Remove(oldPath)
 541	} else {
 542		// On Unix systems, we can directly rename
 543		if err := os.Rename(tmpPath, executablePath); err != nil {
 544			return fmt.Errorf("failed to replace executable: %v", err)
 545		}
 546	}
 547
 548	return nil
 549}
 550
 551func AddNewAnime(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) SelectionOption {
 552	var query string
 553	var animeMapPreview map[string]RofiSelectPreview
 554	var animeOptions []SelectionOption
 555	var err error
 556	var anilistSelectedOption SelectionOption
 557
 558	if userCurdConfig.RofiSelection {
 559		userInput, err := GetUserInputFromRofi("Enter the anime name")
 560		if err != nil {
 561			Log("Error getting user input: " + err.Error())
 562			ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
 563		}
 564		query = userInput
 565	} else {
 566		CurdOut("Enter the anime name:")
 567		reader := bufio.NewReader(os.Stdin)
 568		input, _ := reader.ReadString('\n')
 569		query = strings.TrimSpace(input)
 570	}
 571	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 572		animeMapPreview, err = SearchAnimeAnilistPreview(query, user.Token)
 573	} else {
 574		animeOptions, err = SearchAnimeAnilist(query, user.Token)
 575	}
 576	if err != nil {
 577		Log(fmt.Sprintf("Failed to search anime: %v", err))
 578		ExitCurd(fmt.Errorf("Failed to search anime"))
 579	}
 580	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 581		anilistSelectedOption, err = DynamicSelectPreview(animeMapPreview, false)
 582	} else {
 583		anilistSelectedOption, err = DynamicSelectFromSlice(animeOptions)
 584	}
 585
 586	if anilistSelectedOption.Key == "-1" {
 587		ExitCurd(nil)
 588	}
 589
 590	if err != nil {
 591		Log(fmt.Sprintf("No anime available: %v", err))
 592		ExitCurd(fmt.Errorf("No anime available"))
 593	}
 594	animeID, err := strconv.Atoi(anilistSelectedOption.Key)
 595	if err != nil {
 596		Log(fmt.Sprintf("Failed to convert anime ID to integer: %v", err))
 597		ExitCurd(fmt.Errorf("Failed to convert anime ID to integer"))
 598	}
 599
 600	// Add category selection before adding to list
 601	categories := map[string]string{
 602		"CURRENT":   "Currently Watching",
 603		"COMPLETED": "Completed",
 604		"PAUSED":    "On Hold",
 605		"DROPPED":   "Dropped",
 606		"PLANNING":  "Plan to Watch",
 607	}
 608
 609	ClearScreen()
 610	CurdOut("Select which list to add the anime to:")
 611
 612	categorySelection, err := DynamicSelect(categories)
 613	if err != nil {
 614		Log(fmt.Sprintf("Failed to select category: %v", err))
 615		ExitCurd(fmt.Errorf("Failed to select category"))
 616	}
 617
 618	if categorySelection.Key == "-1" {
 619		ExitCurd(nil)
 620	}
 621
 622	err = UpdateAnimeStatus(user.Token, animeID, categorySelection.Key)
 623	if err != nil {
 624		Log(fmt.Sprintf("Failed to add anime to list: %v", err))
 625		ExitCurd(fmt.Errorf("Failed to add anime to list"))
 626	}
 627
 628	// Refresh user's anime list after adding
 629	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 630		anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id)
 631		if err != nil {
 632			Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
 633			ExitCurd(fmt.Errorf("Failed to refresh anime list"))
 634		}
 635		user.AnimeList = ParseAnimeList(anilistUserDataPreview)
 636	} else {
 637		anilistUserData, err := GetUserData(user.Token, user.Id)
 638		if err != nil {
 639			Log(fmt.Sprintf("Failed to refresh anime list: %v", err))
 640			ExitCurd(fmt.Errorf("Failed to refresh anime list"))
 641		}
 642		user.AnimeList = ParseAnimeList(anilistUserData)
 643	}
 644
 645	return anilistSelectedOption
 646}
 647
 648func SetupCurd(userCurdConfig *CurdConfig, anime *Anime, user *User, databaseAnimes *[]Anime) {
 649	var err error
 650	var anilistUserData map[string]interface{}
 651	var anilistUserDataPreview map[string]interface{}
 652
 653	// Filter anime list based on selected category
 654	var animeListMap map[string]string
 655	var animeListMapPreview map[string]RofiSelectPreview
 656
 657	// Get user id, username and Anime list
 658	user.Id, user.Username, err = GetAnilistUserID(user.Token)
 659	if err != nil {
 660		Log(fmt.Sprintf("Failed to get user ID: %v", err))
 661		ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
 662	}
 663
 664	// Get the anime list data
 665	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 666		anilistUserDataPreview, err = GetUserDataPreview(user.Token, user.Id)
 667		if err != nil {
 668			Log(fmt.Sprintf("Failed to get user data preview: %v", err))
 669			ExitCurd(fmt.Errorf("Failed to get user data preview"))
 670		}
 671		user.AnimeList = ParseAnimeList(anilistUserDataPreview)
 672	} else {
 673		anilistUserData, err = GetUserData(user.Token, user.Id)
 674		if err != nil {
 675			Log(fmt.Sprintf("Failed to get user data: %v", err))
 676			ExitCurd(fmt.Errorf("Failed to get user ID\nYou can reset the token by running `curd -change-token`"))
 677		}
 678		user.AnimeList = ParseAnimeList(anilistUserData)
 679	}
 680
 681	// If continueLast flag is set, directly get the last watched anime
 682	if anime.Ep.ContinueLast {
 683		// Get the last anime ID from the curd_id file
 684		idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
 685		idBytes, err := os.ReadFile(idFilePath)
 686		if err != nil {
 687			Log("Error reading curd_id file: " + err.Error())
 688			ExitCurd(fmt.Errorf("No last watched anime found"))
 689		}
 690
 691		anilistID, err := strconv.Atoi(string(idBytes))
 692		if err != nil {
 693			Log("Error converting anilist ID: " + err.Error())
 694			ExitCurd(fmt.Errorf("Invalid anime ID in curd_id file"))
 695		}
 696
 697		// Find the anime in database
 698		animePointer := LocalFindAnime(*databaseAnimes, anilistID, "")
 699		if animePointer == nil {
 700			ExitCurd(fmt.Errorf("Last watched anime not found in database"))
 701		}
 702
 703		// Set the anime details
 704		anime.AnilistId = animePointer.AnilistId
 705		// anime.AllanimeId = animePointer.AllanimeId
 706		// anime.Title = animePointer.Title
 707		// anime.Ep.Number = animePointer.Ep.Number
 708		// anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
 709		// anime.Ep.Resume = true
 710
 711	} else {
 712		// Skip category selection if Current flag is set
 713		var categorySelection SelectionOption
 714		if userCurdConfig.CurrentCategory {
 715			categorySelection = SelectionOption{
 716				Key:   "CURRENT",
 717				Label: "Currently Watching",
 718			}
 719		} else {
 720			// Create category selection map
 721			categories := getOrderedCategories(userCurdConfig)
 722
 723			// Select category using DynamicSelect
 724			var err error
 725			categorySelection, err = DynamicSelect(categories)
 726			if err != nil {
 727				Log(fmt.Sprintf("Failed to select category: %v", err))
 728				ExitCurd(fmt.Errorf("Failed to select category"))
 729			}
 730
 731			if categorySelection.Key == "-1" {
 732				ExitCurd(nil)
 733			}
 734
 735			// Handle options
 736			if categorySelection.Key == "UPDATE" {
 737				ClearScreen()
 738				UpdateAnimeEntry(userCurdConfig, user)
 739				ExitCurd(nil)
 740			} else if categorySelection.Key == "UNTRACKED" {
 741				ClearScreen()
 742				WatchUntracked(userCurdConfig)
 743			} else if categorySelection.Key == "CONTINUE_LAST" {
 744				anime.Ep.ContinueLast = true
 745			}
 746
 747			ClearScreen()
 748		}
 749
 750		if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 751			animeListMapPreview = make(map[string]RofiSelectPreview)
 752			for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
 753				title := entry.Media.Title.English
 754				if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 755					title = entry.Media.Title.Romaji
 756				}
 757				animeListMapPreview[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 758					Title:      title,
 759					CoverImage: entry.CoverImage,
 760				}
 761			}
 762		} else {
 763			animeListMap = make(map[string]string)
 764			for _, entry := range getEntriesByCategory(user.AnimeList, categorySelection.Key) {
 765				title := entry.Media.Title.English
 766				if title == "" || userCurdConfig.AnimeNameLanguage == "romaji" {
 767					title = entry.Media.Title.Romaji
 768				}
 769				animeListMap[strconv.Itoa(entry.Media.ID)] = title
 770			}
 771		}
 772	}
 773
 774	var anilistSelectedOption SelectionOption
 775	var selectedAllanimeAnime SelectionOption
 776	var userQuery string
 777
 778	if anime.Ep.ContinueLast {
 779		// Get the last watched anime ID from the curd_id file
 780		curdIDPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
 781		curdIDBytes, err := os.ReadFile(curdIDPath)
 782		if err != nil {
 783			Log(fmt.Sprintf("Error reading curd_id file: %v", err))
 784			ExitCurd(fmt.Errorf("Error reading curd_id file"))
 785		}
 786
 787		lastWatchedID, err := strconv.Atoi(strings.TrimSpace(string(curdIDBytes)))
 788		if err != nil {
 789			Log(fmt.Sprintf("Error converting curd_id to integer: %v", err))
 790			ExitCurd(fmt.Errorf("Error converting curd_id to integer"))
 791		}
 792
 793		anime.AnilistId = lastWatchedID
 794		anilistSelectedOption.Key = strconv.Itoa(lastWatchedID)
 795	} else {
 796		// Select anime to watch (Anilist)
 797		var err error
 798		if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 799			anilistSelectedOption, err = DynamicSelectPreview(animeListMapPreview, true)
 800		} else {
 801			// Add "Add new anime" option to the map
 802			animeListMap["add_new"] = "Add new anime"
 803
 804			anilistSelectedOption, err = DynamicSelect(animeListMap)
 805		}
 806		if err != nil {
 807			Log(fmt.Sprintf("Error selecting anime: %v", err))
 808			ExitCurd(fmt.Errorf("Error selecting anime"))
 809		}
 810
 811		Log(anilistSelectedOption)
 812
 813		if anilistSelectedOption.Key == "-1" {
 814			ExitCurd(nil)
 815		}
 816
 817		if anilistSelectedOption.Label == "add_new" || anilistSelectedOption.Key == "add_new" {
 818			anilistSelectedOption = AddNewAnime(userCurdConfig, anime, user, databaseAnimes)
 819		}
 820
 821		anime.AnilistId, err = strconv.Atoi(anilistSelectedOption.Key)
 822		if err != nil {
 823			Log(fmt.Sprintf("Error converting Anilist ID: %v", err))
 824			ExitCurd(fmt.Errorf("Error converting Anilist ID"))
 825		}
 826	}
 827	// Find anime in Local history
 828	animePointer := LocalFindAnime(*databaseAnimes, anime.AnilistId, "")
 829
 830	// Get anime entry
 831	selectedAnilistAnime, err := FindAnimeByAnilistID(user.AnimeList, anilistSelectedOption.Key)
 832	if err != nil {
 833		Log(fmt.Sprintf("Can not find the anime in anilist animelist: %v", err))
 834		ExitCurd(fmt.Errorf("Can not find the anime in anilist animelist"))
 835	}
 836
 837	// Set anime entry
 838	anime.Title = selectedAnilistAnime.Media.Title
 839	anime.TotalEpisodes = selectedAnilistAnime.Media.Episodes
 840	anime.Ep.Number = selectedAnilistAnime.Progress + 1
 841	var animeList map[string]string
 842	userQuery = anime.Title.Romaji
 843
 844	// if anime not found in database, find it in animeList
 845	if animePointer == nil {
 846		Log("Anime not found in database, searching in animeList...")
 847		// Get Anime list (All anime)
 848		Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s", userQuery, userCurdConfig.SubOrDub))
 849
 850		animeList, err = SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
 851		Log(fmt.Sprintf("SearchAnime result - animeList: %+v, err: %v", animeList, err))
 852		if err != nil {
 853			Log(fmt.Sprintf("Failed to select anime: %v", err))
 854			ExitCurd(fmt.Errorf("Failed to select anime"))
 855		}
 856		if len(animeList) == 0 {
 857			ExitCurd(fmt.Errorf("No results found."))
 858		}
 859
 860		// find anime in animeList
 861		anime.AllanimeId, err = FindKeyByValue(animeList, fmt.Sprintf("%v (%d episodes)", userQuery, selectedAnilistAnime.Media.Episodes))
 862		if err != nil {
 863			Log(fmt.Sprintf("Failed to find anime in animeList: %v", err))
 864		}
 865
 866		// If unable to get Allanime id automatically get manually
 867		if anime.AllanimeId == "" {
 868			CurdOut("Failed to automatically select anime")
 869			selectedAllanimeAnime, err := DynamicSelect(animeList)
 870
 871			if selectedAllanimeAnime.Key == "-1" {
 872				ExitCurd(nil)
 873			}
 874
 875			if err != nil {
 876				// fmt.Println("No anime available")
 877				ExitCurd(fmt.Errorf("No anime available"))
 878			}
 879			anime.AllanimeId = selectedAllanimeAnime.Key
 880		}
 881	} else {
 882		// if anime found in database, use it
 883		anime.AllanimeId = animePointer.AllanimeId
 884		anime.Ep.Player.PlaybackTime = animePointer.Ep.Player.PlaybackTime
 885		if anime.Ep.Number == animePointer.Ep.Number {
 886			anime.Ep.Resume = true
 887		}
 888	}
 889
 890	if selectedAllanimeAnime.Key == "-1" {
 891		ExitCurd(nil)
 892	}
 893
 894	// If anime is not in watching list, prompt user to add it into watching list
 895	isInWatchingList := false
 896	for _, entry := range user.AnimeList.Watching {
 897		if entry.Media.ID == anime.AnilistId {
 898			isInWatchingList = true
 899			break
 900		}
 901	}
 902
 903	if !isInWatchingList {
 904		// Create options for the prompt
 905		options := map[string]string{
 906			"yes": "Add to watching list",
 907			"no":  "Continue without adding",
 908		}
 909
 910		var selectedOption SelectionOption
 911		var err error
 912
 913		// Use rofi for selection
 914		selectedOption, err = DynamicSelect(options)
 915		if err != nil {
 916			Log("Error in selection: " + err.Error())
 917			ExitCurd(err)
 918		}
 919
 920		if selectedOption.Key == "yes" {
 921			err = AddAnimeToWatchingList(anime.AnilistId, user.Token)
 922			if err != nil {
 923				Log("Error adding anime to watching list: " + err.Error())
 924				ExitCurd(err)
 925			}
 926			// Refresh user's anime list after adding
 927			if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 928				anilistUserDataPreview, err := GetUserDataPreview(user.Token, user.Id)
 929				if err != nil {
 930					Log("Error refreshing anime list: " + err.Error())
 931					ExitCurd(err)
 932				}
 933				user.AnimeList = ParseAnimeList(anilistUserDataPreview)
 934			} else {
 935				anilistUserData, err := GetUserData(user.Token, user.Id)
 936				if err != nil {
 937					Log("Error refreshing anime list: " + err.Error())
 938					ExitCurd(err)
 939				}
 940				user.AnimeList = ParseAnimeList(anilistUserData)
 941			}
 942		} else if selectedOption.Key == "-1" {
 943			ExitCurd(nil)
 944		}
 945	}
 946
 947	// If upstream is ahead, update the episode number
 948	if temp_anime, err := FindAnimeByAnilistID(user.AnimeList, strconv.Itoa(anime.AnilistId)); err == nil {
 949		if temp_anime.Progress > anime.Ep.Number {
 950			anime.Ep.Number = temp_anime.Progress
 951			anime.Ep.Player.PlaybackTime = 0
 952			anime.Ep.Resume = false
 953		}
 954	}
 955
 956	if anime.TotalEpisodes == 0 {
 957		// Get updated anime data
 958		Log(selectedAllanimeAnime)
 959		updatedAnime, err := GetAnimeDataByID(anime.AnilistId, user.Token)
 960		Log(updatedAnime)
 961		if err != nil {
 962			Log(fmt.Sprintf("Error getting updated anime data: %v", err))
 963		} else {
 964			anime.TotalEpisodes = updatedAnime.TotalEpisodes
 965			Log(fmt.Sprintf("Updated total episodes: %d", anime.TotalEpisodes))
 966		}
 967	}
 968
 969	if anime.TotalEpisodes == 0 { // If failed to get anime data
 970		CurdOut("Failed to get anime data. Attempting to retrieve from anime list.")
 971		animeList, err := SearchAnime(string(userQuery), userCurdConfig.SubOrDub)
 972		if err != nil {
 973			CurdOut(fmt.Sprintf("Failed to retrieve anime list: %v", err))
 974		} else {
 975			for allanimeId, label := range animeList {
 976				if allanimeId == anime.AllanimeId {
 977					// Extract total episodes from the label
 978					if matches := regexp.MustCompile(`\((\d+) episodes\)`).FindStringSubmatch(label); len(matches) > 1 {
 979						anime.TotalEpisodes, _ = strconv.Atoi(matches[1])
 980						CurdOut(fmt.Sprintf("Retrieved total episodes: %d", anime.TotalEpisodes))
 981						break
 982					}
 983				}
 984			}
 985		}
 986
 987		if anime.TotalEpisodes == 0 {
 988			CurdOut("Still unable to determine total episodes.")
 989			CurdOut(fmt.Sprintf("Your AniList progress: %d", selectedAnilistAnime.Progress))
 990			var episodeNumber int
 991			if userCurdConfig.RofiSelection {
 992				userInput, err := GetUserInputFromRofi("Enter the episode you want to start from")
 993				if err != nil {
 994					Log("Error getting user input: " + err.Error())
 995					ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
 996				}
 997				episodeNumber, err = strconv.Atoi(userInput)
 998			} else {
 999				fmt.Print("Enter the episode you want to start from: ")
1000				fmt.Scanln(&episodeNumber)
1001			}
1002			anime.Ep.Number = episodeNumber
1003		} else {
1004			anime.Ep.Number = selectedAnilistAnime.Progress + 1
1005		}
1006	} else if anime.TotalEpisodes < anime.Ep.Number { // Handle weird cases
1007		Log(fmt.Sprintf("Weird case: anime.TotalEpisodes < anime.Ep.Number: %v < %v", anime.TotalEpisodes, anime.Ep.Number))
1008		var answer string
1009		if userCurdConfig.RofiSelection {
1010			userInput, err := GetUserInputFromRofi("Would like to start the anime from beginning? (y/n)")
1011			if err != nil {
1012				Log("Error getting user input: " + err.Error())
1013				ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1014			}
1015			answer = userInput
1016		} else {
1017			fmt.Printf("Would like to start the anime from beginning? (y/n)\n")
1018			fmt.Scanln(&answer)
1019		}
1020		if answer == "y" {
1021			anime.Ep.Number = 1
1022		} else {
1023			anime.Ep.Number = anime.TotalEpisodes
1024		}
1025	}
1026
1027	// Check if this is the last episode - prompt user if needed
1028	if userCurdConfig.NextEpisodePrompt && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !userCurdConfig.RofiSelection {
1029		// Ensure the terminal state is clean for the prompt
1030		fmt.Print("\r\033[K") // Carriage return and clear line
1031	}
1032}
1033
1034// CreateOrWriteTokenFile creates the token file if it doesn't exist and writes the token to it
1035func WriteTokenToFile(token string, filePath string) error {
1036	// Extract the directory path
1037	dir := filepath.Dir(filePath)
1038
1039	// Create all necessary parent directories
1040	if err := os.MkdirAll(dir, 0755); err != nil {
1041		return fmt.Errorf("failed to create directories: %v", err)
1042	}
1043
1044	// Write the token to the file, creating it if it doesn't exist
1045	err := os.WriteFile(filePath, []byte(token), 0644)
1046	if err != nil {
1047		return fmt.Errorf("failed to write token to file: %v", err)
1048	}
1049
1050	return nil
1051}
1052
1053func StartCurd(userCurdConfig *CurdConfig, anime *Anime) string {
1054
1055	if anime.Ep.NextEpisode.Number == anime.Ep.Number {
1056		anime.Ep.Links = anime.Ep.NextEpisode.Links
1057		Log("using prefetched next episode link")
1058	} else {
1059		// Get episode link
1060		link, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1061		if err != nil {
1062			// If unable to get episode link automatically get manually
1063			episodeList, err := EpisodesList(anime.AllanimeId, userCurdConfig.SubOrDub)
1064			if err != nil {
1065				CurdOut("No episode list found")
1066				RestoreScreen()
1067				os.Exit(1)
1068			}
1069			if userCurdConfig.RofiSelection {
1070				userInput, err := GetUserInputFromRofi(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1071				if err != nil {
1072					Log("Error getting user input: " + err.Error())
1073					ExitCurd(fmt.Errorf("Error getting user input: " + err.Error()))
1074				}
1075				anime.Ep.Number, err = strconv.Atoi(userInput)
1076			} else {
1077				CurdOut(fmt.Sprintf("Enter the episode (%v episodes)", episodeList[len(episodeList)-1]))
1078				fmt.Scanln(&anime.Ep.Number)
1079			}
1080			link, err = GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1081			if err != nil {
1082				CurdOut("Failed to get episode link")
1083				os.Exit(1)
1084			}
1085			// anime.Ep.Links = link
1086		}
1087		anime.Ep.Links = link
1088	}
1089
1090	if len(anime.Ep.Links) == 0 {
1091		CurdOut("No episode links found")
1092		os.Exit(1)
1093	}
1094
1095	Log(anime)
1096
1097	// Modify the goroutine in main.go where next episode links are fetched
1098	// Get next episode link in parallel
1099	go func() {
1100		nextEpNum := anime.Ep.Number + 1
1101		if nextEpNum <= anime.TotalEpisodes {
1102			// Get next canon episode number if filler skip is enabled
1103			if userCurdConfig.SkipFiller && IsEpisodeFiller(anime.FillerEpisodes, anime.Ep.Number) {
1104				nextEpNum = GetNextCanonEpisode(anime.FillerEpisodes, nextEpNum)
1105			}
1106			nextLinks, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, nextEpNum)
1107			if err != nil {
1108				Log("Error getting next episode link: " + err.Error())
1109			} else {
1110				anime.Ep.NextEpisode = NextEpisode{
1111					Number: nextEpNum,
1112					Links:  nextLinks,
1113				}
1114				Log(fmt.Sprintf("Next episode link fetched for ep %d", nextEpNum))
1115			}
1116		}
1117	}()
1118
1119	// Write anime.AnilistId to curd_id in the storage path
1120	idFilePath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_id")
1121	Log(fmt.Sprintf("idFilePath: %v", idFilePath))
1122	if err := os.MkdirAll(filepath.Dir(idFilePath), 0755); err != nil {
1123		Log(fmt.Sprintf("Failed to create directory for curd_id: %v", err))
1124	} else {
1125		if err := os.WriteFile(idFilePath, []byte(fmt.Sprintf("%d", anime.AnilistId)), 0644); err != nil {
1126			Log(fmt.Sprintf("Failed to write AnilistId to file: %v", err))
1127		}
1128	}
1129
1130	// Display starting message with cover image and episode info
1131	if anime.CoverImage != "" && userCurdConfig.ImagePreview && userCurdConfig.RofiSelection {
1132		// Get the cached image path
1133		cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
1134		filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(anime.CoverImage)))
1135		cachePath := filepath.Join(cacheDir, filename)
1136
1137		// Display the image if it exists in cache
1138		_, err := os.Stat(cachePath)
1139		if err == nil {
1140			// File exists
1141			Log(fmt.Sprintf("Image found at %s", cachePath))
1142			CurdOut(fmt.Sprintf("-i %s \"%s - Episode %d\"", cachePath, GetAnimeName(*anime), anime.Ep.Number))
1143		} else {
1144			// File does not exist
1145			Log(fmt.Sprintf("Image does not exist at %s", cachePath))
1146			CurdOut(fmt.Sprintf("%s - Episode %d",
1147				GetAnimeName(*anime),
1148				anime.Ep.Number))
1149
1150		}
1151	} else {
1152		CurdOut(fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number))
1153	}
1154	mpvSocketPath, err := StartVideo(PrioritizeLink(anime.Ep.Links), []string{}, fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), anime.Ep.Number), anime)
1155
1156	if err != nil {
1157		Log("Failed to start mpv")
1158		os.Exit(1)
1159	}
1160
1161	return mpvSocketPath
1162}
1163
1164func CheckAndDownloadFiles(storagePath string, filesToCheck []string) error {
1165	// Create storage directory if it doesn't exist
1166	storagePath = os.ExpandEnv(storagePath)
1167	if err := os.MkdirAll(storagePath, 0755); err != nil {
1168		return fmt.Errorf("failed to create storage directory: %v", err)
1169	}
1170
1171	// Base URL for downloading config files
1172	baseURL := "https://raw.githubusercontent.com/Wraient/curd/refs/heads/main/rofi/"
1173
1174	// Check each file
1175	for _, fileName := range filesToCheck {
1176		filePath := filepath.Join(os.ExpandEnv(storagePath), fileName)
1177
1178		// Skip if file already exists
1179		if _, err := os.Stat(filePath); err == nil {
1180			continue
1181		}
1182
1183		// Download file if it doesn't exist
1184		resp, err := http.Get(baseURL + fileName)
1185		if err != nil {
1186			return fmt.Errorf("failed to download %s: %v", fileName, err)
1187		}
1188		defer resp.Body.Close()
1189
1190		// Create the file
1191		out, err := os.Create(filePath)
1192		if err != nil {
1193			return fmt.Errorf("failed to create file %s: %v", fileName, err)
1194		}
1195		defer out.Close()
1196
1197		// Write the content
1198		if _, err := io.Copy(out, resp.Body); err != nil {
1199			return fmt.Errorf("failed to write file %s: %v", fileName, err)
1200		}
1201	}
1202
1203	return nil
1204}
1205
1206func getEntriesByCategory(list AnimeList, category string) []Entry {
1207	switch category {
1208	case "ALL":
1209		// Combine all categories into one slice
1210		allEntries := make([]Entry, 0)
1211		allEntries = append(allEntries, list.Watching...)
1212		allEntries = append(allEntries, list.Completed...)
1213		allEntries = append(allEntries, list.Paused...)
1214		allEntries = append(allEntries, list.Dropped...)
1215		allEntries = append(allEntries, list.Planning...)
1216		return allEntries
1217	case "CURRENT":
1218		return list.Watching
1219	case "COMPLETED":
1220		return list.Completed
1221	case "PAUSED":
1222		return list.Paused
1223	case "DROPPED":
1224		return list.Dropped
1225	case "PLANNING":
1226		return list.Planning
1227	default:
1228		return []Entry{}
1229	}
1230}
1231
1232func NextEpisodePrompt(userCurdConfig *CurdConfig) {
1233	anime := GetGlobalAnime()
1234	// If in CLI mode (not Rofi), we need to show the next episode number
1235	episodeNum := anime.Ep.Number
1236	if !userCurdConfig.RofiSelection {
1237		episodeNum++
1238	}
1239
1240	CurdOut(fmt.Sprintf("Start next episode (%d)?", episodeNum))
1241
1242	// Create options for the selection
1243	options := map[string]string{
1244		"yes": "Yes, start next episode",
1245		// "no":  "No, quit",
1246	}
1247
1248	// Use DynamicSelect for both CLI and Rofi modes
1249	selectedOption, err := DynamicSelect(options)
1250	if err != nil {
1251		Log(fmt.Sprintf("Error in next episode prompt selection: %v", err))
1252		ExitCurd(err)
1253	}
1254
1255	if selectedOption.Key == "-1" {
1256		// User selected to quit
1257		fmt.Print("\r\033[K") // Carriage return and clear line
1258		ExitMPV(anime.Ep.Player.SocketPath)
1259		CurdOut("Exiting without starting next episode")
1260		ExitCurd(nil)
1261		return
1262	}
1263
1264	// If yes, start the next episode
1265	prevEpisode := anime.Ep.Number
1266	anime.Ep.Number++
1267	anime.Ep.Started = false
1268	anime.Ep.IsCompleted = false // Reset completion flag for the new episode
1269
1270	// Clear current line to avoid visual glitches
1271	fmt.Print("\r\033[K") // Carriage return and clear line
1272
1273	CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
1274
1275	// Get database file path for StartNextEpisode
1276	homeDir := ""
1277	if runtime.GOOS == "windows" {
1278		homeDir = os.Getenv("USERPROFILE")
1279	} else {
1280		homeDir = os.Getenv("HOME")
1281	}
1282	configFilePath := filepath.Join(homeDir, ".config", "curd", "curd.conf")
1283	config, err := LoadConfig(configFilePath)
1284	if err != nil {
1285		Log("Error loading config for database path: " + err.Error())
1286		ExitCurd(err)
1287	}
1288	databaseFile := filepath.Join(os.ExpandEnv(config.StoragePath), "curd_history.txt")
1289
1290	// Update local database for the new episode
1291	err = LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, GetAnimeName(*anime))
1292	if err != nil {
1293		Log("Error updating local database: " + err.Error())
1294	}
1295
1296	// Update Anilist progress for the previous episode if not rewatching
1297	if !anime.Rewatching {
1298		user := &User{}
1299		user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(config.StoragePath), "token"))
1300		if err != nil {
1301			Log("Error reading token for progress update: " + err.Error())
1302		} else {
1303			go func() {
1304				err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode)
1305				if err != nil {
1306					Log("Error updating Anilist progress: " + err.Error())
1307				} else {
1308					CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1309				}
1310			}()
1311		}
1312	}
1313
1314	// Close current MPV instance
1315	ExitMPV(anime.Ep.Player.SocketPath)
1316
1317	// Check if we have prefetched links for the next episode
1318	if anime.Ep.NextEpisode.Number == anime.Ep.Number && len(anime.Ep.NextEpisode.Links) > 0 {
1319		Log("Using prefetched next episode link")
1320		anime.Ep.Links = anime.Ep.NextEpisode.Links
1321	} else {
1322		// No prefetched links available, need to fetch them
1323		CurdOut("Fetching links for next episode...")
1324
1325		// Wait for up to 5 seconds for prefetched links to become available
1326		for i := 0; i < 5; i++ {
1327			if anime.Ep.NextEpisode.Number == anime.Ep.Number && len(anime.Ep.NextEpisode.Links) > 0 {
1328				CurdOut("Using newly fetched next episode link")
1329				anime.Ep.Links = anime.Ep.NextEpisode.Links
1330				break
1331			}
1332			time.Sleep(1 * time.Second)
1333		}
1334
1335		// If we still don't have links, get them now
1336		if len(anime.Ep.Links) == 0 {
1337			links, err := GetEpisodeURL(*userCurdConfig, anime.AllanimeId, anime.Ep.Number)
1338			if err != nil {
1339				Log("Failed to get episode links: " + err.Error())
1340				CurdOut("Failed to get episode links. Try again later.")
1341				ExitCurd(fmt.Errorf("failed to get episode links: %v", err))
1342				return
1343			}
1344			anime.Ep.Links = links
1345		}
1346	}
1347
1348	// Verify that we have links before starting
1349	if len(anime.Ep.Links) == 0 {
1350		CurdOut("No episode links found. Try again later.")
1351		ExitCurd(fmt.Errorf("no episode links found"))
1352		return
1353	}
1354
1355	// Actually start the next episode
1356	anime.Ep.Player.SocketPath = StartCurd(userCurdConfig, anime)
1357
1358	// We don't exit, instead we let the main loop continue with the new episode
1359}
1360
1361// StartNextEpisode handles the logic for starting the next episode
1362// It updates the episode number, resets necessary flags, and handles database updates
1363func StartNextEpisode(anime *Anime, userCurdConfig *CurdConfig, databaseFile string) {
1364	// Save previous episode number for progress update
1365	prevEpisode := anime.Ep.Number
1366
1367	// Increment episode number
1368	anime.Ep.Number++
1369
1370	// Check if we've reached the end of the series
1371	if anime.TotalEpisodes > 0 && anime.Ep.Number > anime.TotalEpisodes {
1372		CurdOut("Reached end of series")
1373		ExitCurd(nil)
1374		return
1375	}
1376
1377	// Check if this is the last episode - prompt user if needed
1378	if userCurdConfig.NextEpisodePrompt && anime.TotalEpisodes > 0 && anime.Ep.Number == anime.TotalEpisodes && !userCurdConfig.RofiSelection {
1379		// Ensure the terminal state is clean for the prompt
1380		fmt.Print("\r\033[K") // Carriage return and clear line
1381		CurdOut(fmt.Sprintf("Last episode (%d). Are you sure you want to watch it?", anime.Ep.Number))
1382
1383		// Simple yes/no selection for the last episode
1384		selectedOption, err := DynamicSelect(map[string]string{"yes": "Yes"})
1385		if err != nil {
1386			ExitCurd(err)
1387		}
1388
1389		if selectedOption.Key != "yes" {
1390			// User selected to quitd
1391			fmt.Print("\r\033[K") // Carriage return and clear line
1392			CurdOut("Exiting without watching the last episode.")
1393			ExitCurd(nil)
1394			return
1395		}
1396
1397		// User chose to continue to the last episode
1398		fmt.Print("\r\033[K") // Carriage return and clear line
1399	}
1400
1401	// Reset episode flags
1402	anime.Ep.Started = false
1403	anime.Ep.IsCompleted = false
1404
1405	// Log the transition
1406	Log("Completed episode, starting next.")
1407
1408	// Update local database
1409	err := LocalUpdateAnime(databaseFile, anime.AnilistId, anime.AllanimeId, anime.Ep.Number, 0, 0, GetAnimeName(*anime))
1410	if err != nil {
1411		Log("Error updating local database: " + err.Error())
1412	}
1413
1414	// Update Anilist progress for the previous episode if not rewatching
1415	if !anime.Rewatching {
1416		user := &User{}
1417		user.Token, err = GetTokenFromFile(filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "token"))
1418		if err != nil {
1419			Log("Error reading token for progress update: " + err.Error())
1420		} else {
1421			go func() {
1422				err = UpdateAnimeProgress(user.Token, anime.AnilistId, prevEpisode)
1423				if err != nil {
1424					Log("Error updating Anilist progress: " + err.Error())
1425				} else {
1426					CurdOut(fmt.Sprintf("Anime progress updated! Latest watched episode: %d", prevEpisode))
1427				}
1428			}()
1429		}
1430	}
1431
1432	// Output message to user
1433	CurdOut(fmt.Sprint("Starting next episode: ", anime.Ep.Number))
1434}