internal/curd.go

1594 lines · 50509 bytes · executable

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