internal/anilist.go

1487 lines · 36458 bytes · executable

   1package internal
   2
   3import (
   4	"bytes"
   5	"encoding/json"
   6	"fmt"
   7	"io"
   8	"net/http"
   9	"os"
  10	"path/filepath"
  11	"sort"
  12	"strconv"
  13	"strings"
  14	"time"
  15)
  16
  17// FindKeyByValue searches for a key associated with a given value in a map[string]string
  18func FindKeyByValue(m map[string]string, value string) (string, error) {
  19	for key, val := range m {
  20		if val == value {
  21			return key, nil // Return the key and true if the value is found
  22		}
  23	}
  24	return "", fmt.Errorf("no key with value %v", value) // Return empty string and false if the value is not found
  25}
  26
  27func mediaDisplayTitle(media Media, config *CurdConfig) string {
  28	if media.Title.English != "" && useEnglishAnimeNames(config) {
  29		return media.Title.English
  30	}
  31	if media.Title.Romaji != "" {
  32		return media.Title.Romaji
  33	}
  34	if media.Title.English != "" {
  35		return media.Title.English
  36	}
  37	if media.Title.Japanese != "" {
  38		return media.Title.Japanese
  39	}
  40	if media.ID != 0 {
  41		return strconv.Itoa(media.ID)
  42	}
  43	return "Unknown Anime"
  44}
  45
  46// GetAnimeMap takes an AnimeList and returns a map with media.id as key and media.title.english as value.
  47func GetAnimeMap(animeList AnimeList) map[string]string {
  48	animeMap := make(map[string]string)
  49	userCurdConfig := GetGlobalConfig()
  50
  51	// Helper function to populate the map from a slice of entries
  52	populateMap := func(entries []Entry) {
  53		for _, entry := range entries {
  54			animeMap[strconv.Itoa(entry.Media.ID)] = mediaDisplayTitle(entry.Media, userCurdConfig)
  55		}
  56	}
  57
  58	// Populate the map for each category
  59	populateMap(animeList.Watching)
  60	populateMap(animeList.Completed)
  61	populateMap(animeList.Paused)
  62	populateMap(animeList.Dropped)
  63	populateMap(animeList.Planning)
  64	populateMap(animeList.Rewatching) // Add Rewatching list
  65
  66	return animeMap
  67}
  68
  69// GetAnimeMapPreview takes an AnimeList and returns a map with media.id as key and media.title.english as value.
  70func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
  71	userCurdConfig := GetGlobalConfig()
  72	animeMap := make(map[string]RofiSelectPreview)
  73
  74	// Helper function to populate the map from a slice of entries
  75	populateMap := func(entries []Entry) {
  76		for _, entry := range entries {
  77			animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
  78				Title:      mediaDisplayTitle(entry.Media, userCurdConfig),
  79				CoverImage: entry.CoverImage,
  80			}
  81		}
  82	}
  83
  84	// Populate the map for each category
  85	populateMap(animeList.Watching)
  86	populateMap(animeList.Completed)
  87	populateMap(animeList.Paused)
  88	populateMap(animeList.Dropped)
  89	populateMap(animeList.Planning)
  90	populateMap(animeList.Rewatching) // Add Rewatching list
  91
  92	return animeMap
  93}
  94
  95// fuzzy matching w/ Levenshtein distance
  96func levenshtein(a, b string) int {
  97	a = strings.ToLower(a)
  98	b = strings.ToLower(b)
  99	ar, br := []rune(a), []rune(b)
 100	alen, blen := len(ar), len(br)
 101	if alen == 0 {
 102		return blen
 103	}
 104	if blen == 0 {
 105		return alen
 106	}
 107	matrix := make([][]int, alen+1)
 108	for i := range matrix {
 109		matrix[i] = make([]int, blen+1)
 110	}
 111	for i := 0; i <= alen; i++ {
 112		matrix[i][0] = i
 113	}
 114	for j := 0; j <= blen; j++ {
 115		matrix[0][j] = j
 116	}
 117	for i := 1; i <= alen; i++ {
 118		for j := 1; j <= blen; j++ {
 119			cost := 0
 120			if ar[i-1] != br[j-1] {
 121				cost = 1
 122			}
 123			matrix[i][j] = min3(
 124				matrix[i-1][j]+1,
 125				matrix[i][j-1]+1,
 126				matrix[i-1][j-1]+cost,
 127			)
 128		}
 129	}
 130	return matrix[alen][blen]
 131}
 132
 133func min3(a, b, c int) int {
 134	if a < b && a < c {
 135		return a
 136	}
 137	if b < c {
 138		return b
 139	}
 140	return c
 141}
 142
 143func doAniListSearchRequest(url string, requestBody []byte, token string) ([]byte, error) {
 144	for authAttempt := 0; authAttempt < 2; authAttempt++ {
 145		body, err := doAniListSearchRequestAttempt(url, requestBody, token)
 146		if err == nil {
 147			return body, nil
 148		}
 149		if authAttempt == 0 && isInvalidTokenError(err) {
 150			newToken, renewed, renewErr := tryRenewAniListTokenForAPI(token, "invalid token")
 151			if renewErr != nil {
 152				return nil, renewErr
 153			}
 154			if renewed {
 155				token = newToken
 156				continue
 157			}
 158		}
 159		return nil, err
 160	}
 161
 162	return nil, fmt.Errorf("AniList search failed after token renewal")
 163}
 164
 165func doAniListSearchRequestAttempt(url string, requestBody []byte, token string) ([]byte, error) {
 166	client := sharedHTTPClient
 167	if client == nil {
 168		client = &http.Client{Timeout: 15 * time.Second}
 169	}
 170	for attempt := 0; attempt < 5; attempt++ {
 171		req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
 172		if err != nil {
 173			return nil, fmt.Errorf("failed to create new request: %w", err)
 174		}
 175		if token != "" {
 176			req.Header.Set("Authorization", "Bearer "+token)
 177		}
 178		req.Header.Set("Content-Type", "application/json")
 179
 180		resp, err := client.Do(req)
 181		if err != nil {
 182			return nil, fmt.Errorf("failed to make request: %w", err)
 183		}
 184
 185		body, readErr := io.ReadAll(resp.Body)
 186		resp.Body.Close()
 187		if readErr != nil {
 188			return nil, fmt.Errorf("failed to read response body: %w", readErr)
 189		}
 190		if resp.StatusCode == http.StatusTooManyRequests {
 191			if attempt == 4 {
 192				return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body))
 193			}
 194			time.Sleep(aniListRetryDelay(resp, attempt))
 195			continue
 196		}
 197		if resp.StatusCode != http.StatusOK {
 198			return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body))
 199		}
 200		var envelope map[string]interface{}
 201		if err := json.Unmarshal(body, &envelope); err == nil {
 202			if rawErrors, exists := envelope["errors"]; exists {
 203				errorBody, _ := json.Marshal(rawErrors)
 204				return nil, fmt.Errorf("graphql errors: %s", strings.TrimSpace(string(errorBody)))
 205			}
 206		}
 207		return body, nil
 208	}
 209
 210	return nil, fmt.Errorf("AniList search failed after retries")
 211}
 212
 213// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
 214func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPreview, error) {
 215	url := "https://graphql.anilist.co"
 216
 217	queryString := `
 218	query ($search: String) {
 219		Page(page: 1, perPage: 50) {
 220			media(search: $search, type: ANIME) {
 221				id
 222				episodes
 223				title {
 224					romaji
 225					english
 226					native
 227				}
 228				coverImage {
 229					large
 230				}
 231			}
 232		}
 233	}`
 234
 235	variables := map[string]string{"search": query}
 236	requestBody, err := json.Marshal(map[string]interface{}{
 237		"query":     queryString,
 238		"variables": variables,
 239	})
 240	if err != nil {
 241		return nil, fmt.Errorf("failed to marshal request body: %w", err)
 242	}
 243
 244	body, err := doAniListSearchRequest(url, requestBody, token)
 245	if err != nil {
 246		return nil, err
 247	}
 248
 249	var responseData map[string]ResponseData
 250	err = json.Unmarshal(body, &responseData)
 251	if err != nil {
 252		return nil, fmt.Errorf("failed to unmarshal response: %w", err)
 253	}
 254
 255	animeList := responseData["data"].Page.Media
 256	animeDict := make(map[string]RofiSelectPreview)
 257
 258	type scoredAnime struct {
 259		id       string
 260		title    string
 261		cover    string
 262		episodes int
 263		score    int
 264	}
 265	var scored []scoredAnime
 266	for _, anime := range animeList {
 267		idStr := strconv.Itoa(anime.ID)
 268		title := anime.Title.English
 269		if title == "" {
 270			title = anime.Title.Romaji
 271		}
 272		cover := anime.CoverImage.Large
 273		score := levenshtein(title, query)
 274		scored = append(scored, scoredAnime{idStr, title, cover, anime.Episodes, score})
 275	}
 276	sort.Slice(scored, func(i, j int) bool {
 277		return scored[i].score < scored[j].score
 278	})
 279	for i, s := range scored {
 280		if i >= 10 {
 281			break
 282		}
 283		animeDict[s.id] = RofiSelectPreview{
 284			Title:      FormatAnimeSearchLabel(s.title, s.episodes),
 285			CoverImage: s.cover,
 286		}
 287	}
 288	return animeDict, nil
 289}
 290
 291// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
 292func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
 293	url := "https://graphql.anilist.co"
 294
 295	queryString := `
 296	query ($search: String) {
 297		Page(page: 1, perPage: 50) {
 298			media(search: $search, type: ANIME) {
 299				id
 300				episodes
 301				title {
 302					romaji
 303					english
 304					native
 305				}
 306			}
 307		}
 308	}`
 309
 310	variables := map[string]string{"search": query}
 311	requestBody, err := json.Marshal(map[string]interface{}{
 312		"query":     queryString,
 313		"variables": variables,
 314	})
 315	if err != nil {
 316		return nil, fmt.Errorf("failed to marshal request body: %w", err)
 317	}
 318
 319	body, err := doAniListSearchRequest(url, requestBody, token)
 320	if err != nil {
 321		return nil, err
 322	}
 323
 324	var responseData map[string]ResponseData
 325	err = json.Unmarshal(body, &responseData)
 326	if err != nil {
 327		return nil, fmt.Errorf("failed to unmarshal response: %w", err)
 328	}
 329
 330	animeList := responseData["data"].Page.Media
 331	var results []SelectionOption
 332
 333	type scoredAnime struct {
 334		id       string
 335		title    string
 336		episodes int
 337		score    int
 338	}
 339	var scored []scoredAnime
 340	for _, anime := range animeList {
 341		idStr := strconv.Itoa(anime.ID)
 342		title := anime.Title.English
 343		if title == "" {
 344			title = anime.Title.Romaji
 345		}
 346		score := levenshtein(title, query)
 347		scored = append(scored, scoredAnime{idStr, title, anime.Episodes, score})
 348	}
 349	sort.Slice(scored, func(i, j int) bool {
 350		return scored[i].score < scored[j].score
 351	})
 352	for i, s := range scored {
 353		if i >= 10 {
 354			break
 355		}
 356		results = append(results, SelectionOption{
 357			Key:   s.id,
 358			Label: FormatAnimeSearchLabel(s.title, s.episodes),
 359			Title: s.title,
 360		})
 361	}
 362	return results, nil
 363}
 364
 365// Function to get AniList user ID and username
 366func GetAnilistUserID(token string) (int, string, error) {
 367	url := "https://graphql.anilist.co"
 368	query := `
 369	query {
 370		Viewer {
 371			id
 372			name
 373		}
 374	}`
 375
 376	headers := map[string]string{
 377		"Content-Type": "application/json",
 378		"Accept":       "application/json",
 379	}
 380	if token != "" {
 381		headers["Authorization"] = "Bearer " + token
 382	}
 383
 384	response, err := makePostRequest(url, query, nil, headers)
 385	if err != nil {
 386		return 0, "", err
 387	}
 388
 389	data, ok := response["data"].(map[string]interface{})
 390	if !ok {
 391		return 0, "", fmt.Errorf("invalid AniList viewer response: data field missing")
 392	}
 393	viewer, ok := data["Viewer"].(map[string]interface{})
 394	if !ok || viewer == nil {
 395		return 0, "", fmt.Errorf("invalid AniList viewer response: Viewer field missing")
 396	}
 397	userIDFloat, ok := viewer["id"].(float64)
 398	if !ok {
 399		return 0, "", fmt.Errorf("invalid AniList viewer response: id field missing")
 400	}
 401	userName, _ := viewer["name"].(string)
 402	if userName == "" {
 403		return 0, "", fmt.Errorf("invalid AniList viewer response: name field missing")
 404	}
 405
 406	return int(userIDFloat), userName, nil
 407}
 408
 409// Function to add an anime to the watching list
 410func AddAniListAnimeToWatchingList(animeID int, token string) error {
 411	url := "https://graphql.anilist.co"
 412	mutation := `
 413	mutation ($mediaId: Int) {
 414		SaveMediaListEntry (mediaId: $mediaId, status: CURRENT) {
 415			id
 416			status
 417		}
 418	}`
 419
 420	variables := map[string]interface{}{
 421		"mediaId": animeID,
 422	}
 423
 424	headers := map[string]string{"Content-Type": "application/json"}
 425	if token != "" {
 426		headers["Authorization"] = "Bearer " + token
 427	}
 428
 429	_, err := makePostRequest(url, mutation, variables, headers)
 430	if err != nil {
 431		return fmt.Errorf("failed to add anime: %w", err)
 432	}
 433
 434	CurdOut(fmt.Sprintf("Anime with ID %d has been added to your watching list.", animeID))
 435	return nil
 436}
 437
 438// Function to get MAL ID using AniList media ID
 439func GetAnimeMalID(anilistMediaID int) (int, error) {
 440	url := "https://graphql.anilist.co"
 441	query := `
 442	query ($id: Int) {
 443		Media(id: $id) {
 444			idMal
 445		}
 446	}`
 447
 448	variables := map[string]interface{}{
 449		"id": anilistMediaID,
 450	}
 451
 452	response, err := makePostRequest(url, query, variables, nil)
 453	if err != nil {
 454		return 0, err
 455	}
 456
 457	data, ok := response["data"].(map[string]interface{})
 458	if !ok {
 459		return 0, fmt.Errorf("invalid AniList media response: data field missing")
 460	}
 461	media, ok := data["Media"].(map[string]interface{})
 462	if !ok || media == nil {
 463		return 0, fmt.Errorf("AniList media %d not found", anilistMediaID)
 464	}
 465	malID, ok := media["idMal"].(float64)
 466	if !ok || malID == 0 {
 467		return 0, fmt.Errorf("AniList media %d has no MyAnimeList ID", anilistMediaID)
 468	}
 469	return int(malID), nil
 470}
 471
 472// This function retrieves the MAL ID and cover image URL for an anime from AniList
 473func GetAnimeIDAndImage(anilistMediaID int) (int, string, error) {
 474	url := "https://graphql.anilist.co"
 475	query := `
 476	query ($id: Int) {
 477		Media(id: $id) {
 478			coverImage {
 479				large
 480			}
 481			idMal
 482		}
 483	}`
 484
 485	variables := map[string]interface{}{
 486		"id": anilistMediaID,
 487	}
 488
 489	response, err := makePostRequest(url, query, variables, nil)
 490	if err != nil {
 491		return 0, "", err
 492	}
 493
 494	data, ok := response["data"].(map[string]interface{})
 495	if !ok {
 496		return 0, "", fmt.Errorf("invalid AniList media response: data field missing")
 497	}
 498	media, ok := data["Media"].(map[string]interface{})
 499	if !ok || media == nil {
 500		return 0, "", fmt.Errorf("AniList media %d not found", anilistMediaID)
 501	}
 502	malID := 0
 503	if value, ok := media["idMal"].(float64); ok {
 504		malID = int(value)
 505	}
 506	imageURL := ""
 507	if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
 508		imageURL = safeAniListString(coverImage["large"])
 509	}
 510
 511	return malID, imageURL, nil
 512}
 513
 514// Function to get user data from AniList
 515func GetUserData(token string, userID int) (map[string]interface{}, error) {
 516	query := `
 517	query ($userId: Int, $type: MediaType) {
 518		MediaListCollection(userId: $userId, type: $type) {
 519			lists {
 520				entries {
 521					id
 522					media {
 523						id
 524						idMal
 525						episodes
 526						duration
 527						format
 528						title {
 529							romaji
 530							english
 531							native
 532						}
 533						status
 534					}
 535					status
 536					score
 537					progress
 538					repeat
 539					updatedAt
 540					startedAt {
 541						year
 542						month
 543						day
 544					}
 545					completedAt {
 546						year
 547						month
 548						day
 549					}
 550				}
 551			}
 552		}
 553	}`
 554
 555	variables := map[string]interface{}{
 556		"userId": userID,
 557		"type":   "ANIME",
 558	}
 559
 560	headers := map[string]string{"Content-Type": "application/json"}
 561	if token != "" {
 562		headers["Authorization"] = "Bearer " + token
 563	}
 564
 565	response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers)
 566	if err != nil {
 567		return nil, err
 568	}
 569
 570	return response, nil
 571}
 572
 573func GetUserDataPreview(token string, userID int) (map[string]interface{}, error) {
 574	query := `
 575	query ($userId: Int, $type: MediaType) {
 576		MediaListCollection(userId: $userId, type: $type) {
 577			lists {
 578				entries {
 579					id
 580					media {
 581						id
 582						idMal
 583						episodes
 584						duration
 585						format
 586						coverImage {
 587							large
 588						}
 589						title {
 590							romaji
 591							english
 592							native
 593						}
 594						status
 595					}
 596					status
 597					score
 598					progress
 599					repeat
 600					updatedAt
 601					startedAt {
 602						year
 603						month
 604						day
 605					}
 606					completedAt {
 607						year
 608						month
 609						day
 610					}
 611				}
 612			}
 613		}
 614	}`
 615
 616	variables := map[string]interface{}{
 617		"userId": userID,
 618		"type":   "ANIME",
 619	}
 620
 621	headers := map[string]string{"Content-Type": "application/json"}
 622	if token != "" {
 623		headers["Authorization"] = "Bearer " + token
 624	}
 625
 626	response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers)
 627	if err != nil {
 628		return nil, err
 629	}
 630
 631	return response, nil
 632}
 633
 634// Function to load a JSON file
 635func LoadJSONFile(filePath string) (map[string]interface{}, error) {
 636	data, err := os.ReadFile(filepath.Clean(filePath))
 637	if err != nil {
 638		return nil, fmt.Errorf("failed to read file: %w", err)
 639	}
 640
 641	var jsonData map[string]interface{}
 642	err = json.Unmarshal(data, &jsonData)
 643	if err != nil {
 644		return nil, fmt.Errorf("failed to parse JSON: %w", err)
 645	}
 646
 647	return jsonData, nil
 648}
 649
 650// Function to search for an anime by title in user data
 651func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []map[string]interface{} {
 652	results := []map[string]interface{}{}
 653
 654	data, ok := jsonData["data"].(map[string]interface{})
 655	if !ok {
 656		return results
 657	}
 658	collection, ok := data["MediaListCollection"].(map[string]interface{})
 659	if !ok {
 660		return results
 661	}
 662	lists, ok := collection["lists"].([]interface{})
 663	if !ok {
 664		return results
 665	}
 666	for _, list := range lists {
 667		listMap, ok := list.(map[string]interface{})
 668		if !ok {
 669			continue
 670		}
 671		entries, ok := listMap["entries"].([]interface{})
 672		if !ok {
 673			continue
 674		}
 675		for _, entry := range entries {
 676			entryMap, ok := entry.(map[string]interface{})
 677			if !ok {
 678				continue
 679			}
 680			media, ok := entryMap["media"].(map[string]interface{})
 681			if !ok {
 682				continue
 683			}
 684			title, _ := media["title"].(map[string]interface{})
 685			romajiTitle := safeAniListString(title["romaji"])
 686			englishTitle := safeAniListString(title["english"])
 687			episodes := 0
 688			if value, ok := media["episodes"].(float64); ok {
 689				episodes = int(value)
 690			}
 691			duration := 0
 692			if value, ok := media["duration"].(float64); ok {
 693				duration = int(value)
 694			}
 695
 696			if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) {
 697				result := map[string]interface{}{
 698					"id":            media["id"],
 699					"progress":      entryMap["progress"],
 700					"romaji_title":  romajiTitle,
 701					"english_title": englishTitle,
 702					"episodes":      episodes,
 703					"duration":      duration,
 704				}
 705				results = append(results, result)
 706			}
 707		}
 708	}
 709
 710	return results
 711}
 712
 713// Function to update anime progress
 714func UpdateAniListAnimeProgress(token string, mediaID, progress int) error {
 715	err := SaveAniListAnimeListEntry(token, mediaID, nil, &progress, nil, nil, nil, nil)
 716	if err != nil {
 717		return err
 718	}
 719
 720	CurdOut(fmt.Sprint("Anime progress updated! Latest watched episode: ", progress))
 721	return nil
 722}
 723
 724func UpdateAniListAnimeStatus(token string, mediaID int, status string) error {
 725	err := SaveAniListAnimeListEntry(token, mediaID, &status, nil, nil, nil, nil, nil)
 726	if err != nil {
 727		return fmt.Errorf("failed to update anime status: %w", err)
 728	}
 729
 730	statusMap := map[string]string{
 731		"CURRENT":   "Currently Watching",
 732		"COMPLETED": "Completed",
 733		"PAUSED":    "On Hold",
 734		"DROPPED":   "Dropped",
 735		"PLANNING":  "Plan to Watch",
 736		"REPEATING": "Rewatching",
 737	}
 738
 739	CurdOut(fmt.Sprintf("Anime status updated to: %s", statusMap[status]))
 740	return nil
 741}
 742
 743func SaveAniListAnimeListEntry(token string, mediaID int, status *string, progress *int, repeat *int, score *float64, startedAt *FuzzyDate, completedAt *FuzzyDate) error {
 744	url := "https://graphql.anilist.co"
 745	query := `
 746	mutation(
 747		$mediaId: Int
 748		$status: MediaListStatus
 749		$progress: Int
 750		$repeat: Int
 751		$score: Float
 752		$startedAt: FuzzyDateInput
 753		$completedAt: FuzzyDateInput
 754	) {
 755		SaveMediaListEntry(
 756			mediaId: $mediaId
 757			status: $status
 758			progress: $progress
 759			repeat: $repeat
 760			score: $score
 761			startedAt: $startedAt
 762			completedAt: $completedAt
 763		) {
 764			id
 765			status
 766			progress
 767			repeat
 768			startedAt {
 769				year
 770				month
 771				day
 772			}
 773			completedAt {
 774				year
 775				month
 776				day
 777			}
 778		}
 779	}`
 780
 781	variables := map[string]interface{}{
 782		"mediaId": mediaID,
 783	}
 784	if status != nil {
 785		variables["status"] = *status
 786	}
 787	if progress != nil {
 788		variables["progress"] = *progress
 789	}
 790	if repeat != nil {
 791		variables["repeat"] = *repeat
 792	}
 793	if score != nil {
 794		variables["score"] = *score
 795	}
 796	if startedAt != nil {
 797		if startedAt.Year == 0 && startedAt.Month == 0 && startedAt.Day == 0 {
 798			variables["startedAt"] = nil
 799		} else {
 800			variables["startedAt"] = map[string]int{
 801				"year":  startedAt.Year,
 802				"month": startedAt.Month,
 803				"day":   startedAt.Day,
 804			}
 805		}
 806	}
 807	if completedAt != nil {
 808		if completedAt.Year == 0 && completedAt.Month == 0 && completedAt.Day == 0 {
 809			variables["completedAt"] = nil
 810		} else {
 811			variables["completedAt"] = map[string]int{
 812				"year":  completedAt.Year,
 813				"month": completedAt.Month,
 814				"day":   completedAt.Day,
 815			}
 816		}
 817	}
 818
 819	headers := map[string]string{
 820		"Authorization": "Bearer " + token,
 821		"Content-Type":  "application/json",
 822	}
 823
 824	_, err := makePostRequest(url, query, variables, headers)
 825	if err != nil {
 826		return err
 827	}
 828	return nil
 829}
 830
 831func CompleteAniListAnimeRewatch(token string, anime Anime) error {
 832	status := "COMPLETED"
 833	progress := anime.Ep.Number
 834	repeat := anime.Repeat + 1
 835	completedAt := currentFuzzyDate()
 836	startedAt := anime.StartedAt
 837	if startedAt == (FuzzyDate{}) {
 838		startedAt = completedAt
 839	}
 840	return SaveAniListAnimeListEntry(token, anime.AnilistId, &status, &progress, &repeat, nil, &startedAt, &completedAt)
 841}
 842
 843// Function to rate an anime on AniList
 844func RateAniListAnime(token string, mediaID int) error {
 845	score, err := promptAnimeScoreValue()
 846	if err != nil {
 847		return err
 848	}
 849	return saveAniListAnimeScore(token, mediaID, score)
 850}
 851
 852func saveAniListAnimeScore(token string, mediaID int, score float64) error {
 853	url := "https://graphql.anilist.co"
 854	query := `
 855	mutation($mediaId: Int, $score: Float) {
 856		SaveMediaListEntry(mediaId: $mediaId, score: $score) {
 857			id
 858			mediaId
 859			score
 860		}
 861	}`
 862
 863	variables := map[string]interface{}{
 864		"mediaId": mediaID,
 865		"score":   score,
 866	}
 867
 868	headers := map[string]string{
 869		"Authorization": "Bearer " + token,
 870		"Content-Type":  "application/json",
 871	}
 872
 873	_, err := makePostRequest(url, query, variables, headers)
 874	if err != nil {
 875		return err
 876	}
 877
 878	CurdOut(fmt.Sprintf("Successfully rated anime (mediaId: %d) with score: %.2f", mediaID, score))
 879	return nil
 880}
 881
 882func aniListRetryDelay(resp *http.Response, attempt int) time.Duration {
 883	if resp != nil {
 884		if retryAfter := strings.TrimSpace(resp.Header.Get("Retry-After")); retryAfter != "" {
 885			if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds > 0 {
 886				return time.Duration(seconds) * time.Second
 887			}
 888		}
 889	}
 890
 891	return time.Duration(attempt+1) * 2 * time.Second
 892}
 893
 894// Helper function to make POST requests
 895func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) {
 896	requestBody, err := json.Marshal(map[string]interface{}{
 897		"query":     query,
 898		"variables": variables,
 899	})
 900	if err != nil {
 901		return nil, fmt.Errorf("failed to marshal request body: %w", err)
 902	}
 903
 904	token := ""
 905	if headers != nil {
 906		if authHeader := headers["Authorization"]; strings.HasPrefix(authHeader, "Bearer ") {
 907			token = strings.TrimPrefix(authHeader, "Bearer ")
 908		}
 909	}
 910
 911	for authAttempt := 0; authAttempt < 2; authAttempt++ {
 912		response, err := makePostRequestAttempt(url, requestBody, headers)
 913		if err == nil {
 914			return response, nil
 915		}
 916		if authAttempt == 0 && isInvalidTokenError(err) && token != "" {
 917			newToken, renewed, renewErr := tryRenewAniListTokenForAPI(token, "invalid token")
 918			if renewErr != nil {
 919				return nil, renewErr
 920			}
 921			if renewed {
 922				token = newToken
 923				if headers == nil {
 924					headers = map[string]string{}
 925				}
 926				headers["Authorization"] = "Bearer " + newToken
 927				continue
 928			}
 929		}
 930		return nil, err
 931	}
 932
 933	return nil, fmt.Errorf("AniList request failed after token renewal")
 934}
 935
 936func makePostRequestAttempt(url string, requestBody []byte, headers map[string]string) (map[string]interface{}, error) {
 937	client := sharedHTTPClient
 938	if client == nil {
 939		client = &http.Client{Timeout: 15 * time.Second}
 940	}
 941	for attempt := 0; attempt < 5; attempt++ {
 942		req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
 943		if err != nil {
 944			return nil, fmt.Errorf("failed to create request: %w", err)
 945		}
 946
 947		req.Header.Set("Content-Type", "application/json")
 948		for key, value := range headers {
 949			req.Header.Set(key, value)
 950		}
 951
 952		resp, err := client.Do(req)
 953		if err != nil {
 954			return nil, fmt.Errorf("failed to send request: %w", err)
 955		}
 956
 957		body, readErr := io.ReadAll(resp.Body)
 958		resp.Body.Close()
 959		if readErr != nil {
 960			return nil, fmt.Errorf("failed to read response body: %w", readErr)
 961		}
 962
 963		if resp.StatusCode == http.StatusTooManyRequests {
 964			if attempt == 4 {
 965				return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
 966			}
 967			time.Sleep(aniListRetryDelay(resp, attempt))
 968			continue
 969		}
 970		if resp.StatusCode != http.StatusOK {
 971			return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
 972		}
 973
 974		var responseData map[string]interface{}
 975		if err := json.Unmarshal(body, &responseData); err != nil {
 976			return nil, fmt.Errorf("failed to unmarshal response: %w", err)
 977		}
 978		if rawErrors, exists := responseData["errors"]; exists {
 979			errorBody, _ := json.Marshal(rawErrors)
 980			return nil, fmt.Errorf("graphql errors: %s", strings.TrimSpace(string(errorBody)))
 981		}
 982
 983		return responseData, nil
 984	}
 985
 986	return nil, fmt.Errorf("AniList request failed after retries")
 987}
 988
 989func ParseAnimeList(input map[string]interface{}) AnimeList {
 990	var animeList AnimeList
 991
 992	toInt := func(value interface{}) int {
 993		switch v := value.(type) {
 994		case int:
 995			return v
 996		case float64:
 997			return int(v) // You could also use int(math.Round(v)) to round
 998		default:
 999			return 0 // Default value for unexpected types
1000		}
1001	}
1002
1003	safeString := func(value interface{}) string {
1004		if value == nil {
1005			return ""
1006		}
1007
1008		// Attempt to assert the value as a string
1009		if str, ok := value.(string); ok {
1010			return str
1011		}
1012
1013		// If it's not a string, return an empty string or handle it as needed
1014		return ""
1015	}
1016
1017	parseFuzzyDate := func(value interface{}) FuzzyDate {
1018		dateMap, ok := value.(map[string]interface{})
1019		if !ok || dateMap == nil {
1020			return FuzzyDate{}
1021		}
1022
1023		return FuzzyDate{
1024			Year:  toInt(dateMap["year"]),
1025			Month: toInt(dateMap["month"]),
1026			Day:   toInt(dateMap["day"]),
1027		}
1028	}
1029
1030	if input == nil {
1031		Log("AniList response is nil")
1032		return animeList
1033	}
1034
1035	// Access the list entries in the input map
1036	if input["data"] == nil {
1037		Log("Anilist request failed")
1038		return animeList
1039	}
1040	data, ok := input["data"].(map[string]interface{})
1041	if !ok {
1042		Log("AniList response data field is invalid")
1043		return animeList
1044	}
1045	collection, ok := data["MediaListCollection"].(map[string]interface{})
1046	if !ok {
1047		Log("AniList response MediaListCollection field is invalid")
1048		return animeList
1049	}
1050	mediaList, ok := collection["lists"].([]interface{})
1051	if !ok {
1052		Log("AniList response lists field is invalid")
1053		return animeList
1054	}
1055
1056	for _, list := range mediaList {
1057		listData, ok := list.(map[string]interface{})
1058		if !ok {
1059			continue
1060		}
1061		entries, ok := listData["entries"].([]interface{})
1062		if !ok {
1063			continue
1064		}
1065
1066		for _, entry := range entries {
1067			entryData, ok := entry.(map[string]interface{})
1068			if !ok {
1069				continue
1070			}
1071			media, ok := entryData["media"].(map[string]interface{})
1072			if !ok {
1073				continue
1074			}
1075			title, _ := media["title"].(map[string]interface{})
1076			animeEntry := Entry{
1077				ListID: toInt(entryData["id"]),
1078				Media: Media{
1079					Duration: toInt(media["duration"]),
1080					Episodes: toInt(media["episodes"]),
1081					Format:   safeString(media["format"]),
1082					ID:       toInt(media["id"]),
1083					MalID:    toInt(media["idMal"]),
1084					Title: AnimeTitle{
1085						English:  safeString(title["english"]),
1086						Romaji:   safeString(title["romaji"]),
1087						Japanese: safeString(title["native"]),
1088					},
1089					Status: safeString(media["status"]),
1090				},
1091				Progress:    toInt(entryData["progress"]),
1092				Repeat:      toInt(entryData["repeat"]),
1093				Status:      safeString(entryData["status"]), // Ensure status is fetched safely
1094				StartedAt:   parseFuzzyDate(entryData["startedAt"]),
1095				CompletedAt: parseFuzzyDate(entryData["completedAt"]),
1096				UpdatedAt:   time.Unix(int64(toInt(entryData["updatedAt"])), 0).UTC(),
1097			}
1098			if score, ok := entryData["score"].(float64); ok {
1099				animeEntry.Score = score
1100			}
1101
1102			if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
1103				animeEntry.CoverImage = safeString(coverImage["large"])
1104			}
1105
1106			// Append entries based on their status
1107			switch animeEntry.Status {
1108			case "CURRENT":
1109				animeList.Watching = append(animeList.Watching, animeEntry)
1110			case "COMPLETED":
1111				animeList.Completed = append(animeList.Completed, animeEntry)
1112			case "PAUSED":
1113				animeList.Paused = append(animeList.Paused, animeEntry)
1114			case "DROPPED":
1115				animeList.Dropped = append(animeList.Dropped, animeEntry)
1116			case "PLANNING":
1117				animeList.Planning = append(animeList.Planning, animeEntry)
1118			case "REPEATING": // Anilist uses REPEATING for rewatching
1119				animeList.Rewatching = append(animeList.Rewatching, animeEntry)
1120			}
1121		}
1122	}
1123
1124	return animeList
1125}
1126
1127// FindAnimeByID searches for an anime by its ID in the AnimeList
1128func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
1129	id, err := strconv.Atoi(idStr)
1130	if err != nil {
1131		return nil, fmt.Errorf("invalid ID format: %s", idStr)
1132	}
1133
1134	// Define a slice of pointers to hold categories
1135	categories := [][]Entry{
1136		list.Watching,
1137		list.Completed,
1138		list.Paused,
1139		list.Dropped,
1140		list.Planning,
1141		list.Rewatching, // Add Rewatching list
1142	}
1143
1144	// Iterate through each category
1145	for _, category := range categories {
1146		for _, entry := range category {
1147			if entry.Media.ID == id {
1148				return &entry, nil // Return a pointer to the found entry
1149			}
1150		}
1151	}
1152
1153	return nil, fmt.Errorf("anime with ID %d not found", id) // Return an error if not found
1154}
1155
1156// FindAnimeByAnilistIDInAnimes searches for an anime by its AniList ID in a slice of Anime
1157func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error) {
1158	for i := range animes {
1159		if animes[i].AnilistId == anilistID {
1160			return &animes[i], nil
1161		}
1162	}
1163	return nil, fmt.Errorf("anime with ID %d not found", anilistID)
1164}
1165
1166// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token
1167func GetAnimeDataByID(id int, token string) (Anime, error) {
1168	url := "https://graphql.anilist.co"
1169	query := `
1170	query ($id: Int) {
1171		Media(id: $id, type: ANIME) {
1172			id
1173			idMal
1174			episodes
1175			duration
1176			status
1177			title {
1178				romaji
1179				english
1180				native
1181			}
1182			coverImage {
1183				large
1184			}
1185			nextAiringEpisode {
1186				episode
1187			}
1188		}
1189	}`
1190
1191	variables := map[string]interface{}{
1192		"id": id,
1193	}
1194
1195	headers := map[string]string{"Content-Type": "application/json"}
1196	if token != "" {
1197		headers["Authorization"] = "Bearer " + token
1198	}
1199
1200	response, err := makePostRequest(url, query, variables, headers)
1201	if err != nil {
1202		return Anime{}, fmt.Errorf("failed to get anime data: %w", err)
1203	}
1204
1205	data, ok := response["data"].(map[string]interface{})
1206	if !ok {
1207		return Anime{}, fmt.Errorf("invalid response format: data field missing")
1208	}
1209
1210	media, ok := data["Media"].(map[string]interface{})
1211	if !ok {
1212		return Anime{}, fmt.Errorf("invalid response format: Media field missing")
1213	}
1214
1215	anime := Anime{
1216		AnilistId: id,
1217		IsAiring:  false,
1218	}
1219
1220	if malID, ok := media["idMal"].(float64); ok {
1221		anime.MalId = int(malID)
1222	}
1223
1224	// Safely handle episodes field which might be nil for currently airing shows
1225	if episodes, ok := media["episodes"].(float64); ok {
1226		anime.TotalEpisodes = int(episodes)
1227	}
1228	if duration, ok := media["duration"].(float64); ok {
1229		anime.Ep.Duration = int(duration) * 60
1230	}
1231	if title, ok := media["title"].(map[string]interface{}); ok {
1232		anime.Title = AnimeTitle{
1233			Romaji:   safeAniListString(title["romaji"]),
1234			English:  safeAniListString(title["english"]),
1235			Japanese: safeAniListString(title["native"]),
1236		}
1237	}
1238	if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
1239		anime.CoverImage = safeAniListString(coverImage["large"])
1240	}
1241
1242	// Check status
1243	if status, ok := media["status"].(string); ok {
1244		anime.IsAiring = status == "RELEASING"
1245	}
1246
1247	// Double check with nextAiringEpisode
1248	if nextEp, ok := media["nextAiringEpisode"].(map[string]interface{}); ok && nextEp != nil {
1249		anime.IsAiring = true
1250	}
1251
1252	return anime, nil
1253}
1254
1255// SequelInfo holds information about a sequel anime
1256type SequelInfo struct {
1257	ID         int
1258	Title      AnimeTitle
1259	CoverImage string
1260	Episodes   int
1261	Status     string // "FINISHED", "RELEASING", "NOT_YET_RELEASED"
1262	SiteURL    string
1263}
1264
1265// GetAnimeSequel fetches sequel information for a given anime from AniList
1266// GetAnimeSequel fetches sequel information for a given anime from AniList
1267func GetAnimeSequel(animeID int, token string) ([]SequelInfo, error) {
1268	url := "https://graphql.anilist.co"
1269	query := `
1270	query ($id: Int) {
1271		Media(id: $id, type: ANIME) {
1272			relations {
1273				edges {
1274					relationType
1275					node {
1276						id
1277						title {
1278							romaji
1279							english
1280						}
1281						coverImage {
1282							large
1283						}
1284						episodes
1285						status
1286						siteUrl
1287					}
1288				}
1289			}
1290		}
1291	}`
1292
1293	variables := map[string]interface{}{
1294		"id": animeID,
1295	}
1296
1297	headers := map[string]string{"Content-Type": "application/json"}
1298	if token != "" {
1299		headers["Authorization"] = "Bearer " + token
1300	}
1301
1302	response, err := makePostRequest(url, query, variables, headers)
1303	if err != nil {
1304		return nil, fmt.Errorf("failed to get anime relations: %w", err)
1305	}
1306
1307	data, ok := response["data"].(map[string]interface{})
1308	if !ok {
1309		return nil, fmt.Errorf("invalid response format: data field missing")
1310	}
1311
1312	media, ok := data["Media"].(map[string]interface{})
1313	if !ok {
1314		return nil, fmt.Errorf("invalid response format: Media field missing")
1315	}
1316
1317	relations, ok := media["relations"].(map[string]interface{})
1318	if !ok {
1319		return nil, nil // No relations found
1320	}
1321
1322	edges, ok := relations["edges"].([]interface{})
1323	if !ok || len(edges) == 0 {
1324		return nil, nil // No edges found
1325	}
1326
1327	var sequels []SequelInfo
1328
1329	// Look for a SEQUEL relation
1330	for _, edge := range edges {
1331		edgeData, ok := edge.(map[string]interface{})
1332		if !ok {
1333			continue
1334		}
1335
1336		relationType, ok := edgeData["relationType"].(string)
1337		if !ok || relationType != "SEQUEL" {
1338			continue
1339		}
1340
1341		node, ok := edgeData["node"].(map[string]interface{})
1342		if !ok {
1343			continue
1344		}
1345
1346		var sequel SequelInfo
1347
1348		// Parse ID
1349		if id, ok := node["id"].(float64); ok {
1350			sequel.ID = int(id)
1351		}
1352
1353		// Parse title
1354		if title, ok := node["title"].(map[string]interface{}); ok {
1355			if romaji, ok := title["romaji"].(string); ok {
1356				sequel.Title.Romaji = romaji
1357			}
1358			if english, ok := title["english"].(string); ok {
1359				sequel.Title.English = english
1360			}
1361		}
1362
1363		// Parse cover image
1364		if coverImage, ok := node["coverImage"].(map[string]interface{}); ok {
1365			if large, ok := coverImage["large"].(string); ok {
1366				sequel.CoverImage = large
1367			}
1368		}
1369
1370		// Parse episodes
1371		if episodes, ok := node["episodes"].(float64); ok {
1372			sequel.Episodes = int(episodes)
1373		}
1374
1375		// Parse status
1376		if status, ok := node["status"].(string); ok {
1377			sequel.Status = status
1378		}
1379
1380		// Parse siteUrl
1381		if siteUrl, ok := node["siteUrl"].(string); ok {
1382			sequel.SiteURL = siteUrl
1383		}
1384
1385		sequels = append(sequels, sequel)
1386	}
1387
1388	if len(sequels) == 0 {
1389		return nil, nil // No sequel found
1390	}
1391
1392	return sequels, nil
1393}
1394
1395// AddAnimeToList adds an anime to a specified list (CURRENT, PLANNING, PAUSED, DROPPED)
1396func AddAniListAnimeToList(animeID int, status string, token string) error {
1397	url := "https://graphql.anilist.co"
1398	mutation := `
1399	mutation ($mediaId: Int, $status: MediaListStatus) {
1400		SaveMediaListEntry (mediaId: $mediaId, status: $status) {
1401			id
1402			status
1403		}
1404	}`
1405
1406	variables := map[string]interface{}{
1407		"mediaId": animeID,
1408		"status":  status,
1409	}
1410
1411	headers := map[string]string{
1412		"Authorization": "Bearer " + token,
1413		"Content-Type":  "application/json",
1414	}
1415
1416	_, err := makePostRequest(url, mutation, variables, headers)
1417	if err != nil {
1418		return fmt.Errorf("failed to add anime to list: %w", err)
1419	}
1420
1421	statusMap := map[string]string{
1422		"CURRENT":   "Currently Watching",
1423		"COMPLETED": "Completed",
1424		"PAUSED":    "On Hold",
1425		"DROPPED":   "Dropped",
1426		"PLANNING":  "Plan to Watch",
1427		"REPEATING": "Rewatching",
1428	}
1429
1430	CurdOut(fmt.Sprintf("Anime added to: %s", statusMap[status]))
1431	return nil
1432}
1433
1434func DeleteAniListListEntry(token string, listID int) error {
1435	url := "https://graphql.anilist.co"
1436	query := `
1437	mutation ($id: Int) {
1438		DeleteMediaListEntry(id: $id) {
1439			deleted
1440		}
1441	}`
1442
1443	headers := map[string]string{"Content-Type": "application/json"}
1444	if token != "" {
1445		headers["Authorization"] = "Bearer " + token
1446	}
1447
1448	_, err := makePostRequest(url, query, map[string]interface{}{"id": listID}, headers)
1449	return err
1450}
1451
1452// FindSequelInAnimeList searches for a sequel in the user's anime list and returns its status
1453func FindSequelInAnimeList(list AnimeList, sequelID int) (string, bool) {
1454	// Check all categories
1455	for _, entry := range list.Watching {
1456		if entry.Media.ID == sequelID {
1457			return "CURRENT", true
1458		}
1459	}
1460	for _, entry := range list.Planning {
1461		if entry.Media.ID == sequelID {
1462			return "PLANNING", true
1463		}
1464	}
1465	for _, entry := range list.Completed {
1466		if entry.Media.ID == sequelID {
1467			return "COMPLETED", true
1468		}
1469	}
1470	for _, entry := range list.Paused {
1471		if entry.Media.ID == sequelID {
1472			return "PAUSED", true
1473		}
1474	}
1475	for _, entry := range list.Dropped {
1476		if entry.Media.ID == sequelID {
1477			return "DROPPED", true
1478		}
1479	}
1480	for _, entry := range list.Rewatching {
1481		if entry.Media.ID == sequelID {
1482			return "REWATCHING", true
1483		}
1484	}
1485
1486	return "", false
1487}