internal/curd.go

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