internal/anilist.go

1557 lines · 38328 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				name
 521				isCustomList
 522				entries {
 523					id
 524					media {
 525						id
 526						idMal
 527						episodes
 528						duration
 529						format
 530						title {
 531							romaji
 532							english
 533							native
 534						}
 535						status
 536					}
 537					status
 538					score
 539					progress
 540					repeat
 541					updatedAt
 542					startedAt {
 543						year
 544						month
 545						day
 546					}
 547					completedAt {
 548						year
 549						month
 550						day
 551					}
 552				}
 553			}
 554		}
 555	}`
 556
 557	variables := map[string]interface{}{
 558		"userId": userID,
 559		"type":   "ANIME",
 560	}
 561
 562	headers := map[string]string{"Content-Type": "application/json"}
 563	if token != "" {
 564		headers["Authorization"] = "Bearer " + token
 565	}
 566
 567	response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers)
 568	if err != nil {
 569		return nil, err
 570	}
 571
 572	return response, nil
 573}
 574
 575func GetUserDataPreview(token string, userID int) (map[string]interface{}, error) {
 576	query := `
 577	query ($userId: Int, $type: MediaType) {
 578		MediaListCollection(userId: $userId, type: $type) {
 579			lists {
 580				name
 581				isCustomList
 582				entries {
 583					id
 584					media {
 585						id
 586						idMal
 587						episodes
 588						duration
 589						format
 590						coverImage {
 591							large
 592						}
 593						title {
 594							romaji
 595							english
 596							native
 597						}
 598						status
 599					}
 600					status
 601					score
 602					progress
 603					repeat
 604					updatedAt
 605					startedAt {
 606						year
 607						month
 608						day
 609					}
 610					completedAt {
 611						year
 612						month
 613						day
 614					}
 615				}
 616			}
 617		}
 618	}`
 619
 620	variables := map[string]interface{}{
 621		"userId": userID,
 622		"type":   "ANIME",
 623	}
 624
 625	headers := map[string]string{"Content-Type": "application/json"}
 626	if token != "" {
 627		headers["Authorization"] = "Bearer " + token
 628	}
 629
 630	response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers)
 631	if err != nil {
 632		return nil, err
 633	}
 634
 635	return response, nil
 636}
 637
 638// Function to load a JSON file
 639func LoadJSONFile(filePath string) (map[string]interface{}, error) {
 640	data, err := os.ReadFile(filepath.Clean(filePath))
 641	if err != nil {
 642		return nil, fmt.Errorf("failed to read file: %w", err)
 643	}
 644
 645	var jsonData map[string]interface{}
 646	err = json.Unmarshal(data, &jsonData)
 647	if err != nil {
 648		return nil, fmt.Errorf("failed to parse JSON: %w", err)
 649	}
 650
 651	return jsonData, nil
 652}
 653
 654// Function to search for an anime by title in user data
 655func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []map[string]interface{} {
 656	results := []map[string]interface{}{}
 657
 658	data, ok := jsonData["data"].(map[string]interface{})
 659	if !ok {
 660		return results
 661	}
 662	collection, ok := data["MediaListCollection"].(map[string]interface{})
 663	if !ok {
 664		return results
 665	}
 666	lists, ok := collection["lists"].([]interface{})
 667	if !ok {
 668		return results
 669	}
 670	seenMediaIDs := make(map[int]struct{})
 671	for _, list := range lists {
 672		listMap, ok := list.(map[string]interface{})
 673		if !ok {
 674			continue
 675		}
 676		// Custom lists re-export status-list entries and would create search hits twice.
 677		if isAniListCustomList(listMap) {
 678			continue
 679		}
 680		entries, ok := listMap["entries"].([]interface{})
 681		if !ok {
 682			continue
 683		}
 684		for _, entry := range entries {
 685			entryMap, ok := entry.(map[string]interface{})
 686			if !ok {
 687				continue
 688			}
 689			media, ok := entryMap["media"].(map[string]interface{})
 690			if !ok {
 691				continue
 692			}
 693			title, _ := media["title"].(map[string]interface{})
 694			romajiTitle := safeAniListString(title["romaji"])
 695			englishTitle := safeAniListString(title["english"])
 696			episodes := 0
 697			if value, ok := media["episodes"].(float64); ok {
 698				episodes = int(value)
 699			}
 700			duration := 0
 701			if value, ok := media["duration"].(float64); ok {
 702				duration = int(value)
 703			}
 704			mediaID := 0
 705			switch id := media["id"].(type) {
 706			case float64:
 707				mediaID = int(id)
 708			case int:
 709				mediaID = id
 710			}
 711
 712			if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) {
 713				if mediaID != 0 {
 714					if _, seen := seenMediaIDs[mediaID]; seen {
 715						continue
 716					}
 717					seenMediaIDs[mediaID] = struct{}{}
 718				}
 719				result := map[string]interface{}{
 720					"id":            media["id"],
 721					"progress":      entryMap["progress"],
 722					"romaji_title":  romajiTitle,
 723					"english_title": englishTitle,
 724					"episodes":      episodes,
 725					"duration":      duration,
 726				}
 727				results = append(results, result)
 728			}
 729		}
 730	}
 731
 732	return results
 733}
 734
 735// Function to update anime progress
 736func UpdateAniListAnimeProgress(token string, mediaID, progress int) error {
 737	err := SaveAniListAnimeListEntry(token, mediaID, nil, &progress, nil, nil, nil, nil)
 738	if err != nil {
 739		return err
 740	}
 741
 742	CurdOut(fmt.Sprint("Anime progress updated! Latest watched episode: ", progress))
 743	return nil
 744}
 745
 746func UpdateAniListAnimeStatus(token string, mediaID int, status string) error {
 747	err := SaveAniListAnimeListEntry(token, mediaID, &status, nil, nil, nil, nil, nil)
 748	if err != nil {
 749		return fmt.Errorf("failed to update anime status: %w", err)
 750	}
 751
 752	statusMap := map[string]string{
 753		"CURRENT":   "Currently Watching",
 754		"COMPLETED": "Completed",
 755		"PAUSED":    "On Hold",
 756		"DROPPED":   "Dropped",
 757		"PLANNING":  "Plan to Watch",
 758		"REPEATING": "Rewatching",
 759	}
 760
 761	CurdOut(fmt.Sprintf("Anime status updated to: %s", statusMap[status]))
 762	return nil
 763}
 764
 765func SaveAniListAnimeListEntry(token string, mediaID int, status *string, progress *int, repeat *int, score *float64, startedAt *FuzzyDate, completedAt *FuzzyDate) error {
 766	url := "https://graphql.anilist.co"
 767	query := `
 768	mutation(
 769		$mediaId: Int
 770		$status: MediaListStatus
 771		$progress: Int
 772		$repeat: Int
 773		$score: Float
 774		$startedAt: FuzzyDateInput
 775		$completedAt: FuzzyDateInput
 776	) {
 777		SaveMediaListEntry(
 778			mediaId: $mediaId
 779			status: $status
 780			progress: $progress
 781			repeat: $repeat
 782			score: $score
 783			startedAt: $startedAt
 784			completedAt: $completedAt
 785		) {
 786			id
 787			status
 788			progress
 789			repeat
 790			startedAt {
 791				year
 792				month
 793				day
 794			}
 795			completedAt {
 796				year
 797				month
 798				day
 799			}
 800		}
 801	}`
 802
 803	variables := map[string]interface{}{
 804		"mediaId": mediaID,
 805	}
 806	if status != nil {
 807		variables["status"] = *status
 808	}
 809	if progress != nil {
 810		variables["progress"] = *progress
 811	}
 812	if repeat != nil {
 813		variables["repeat"] = *repeat
 814	}
 815	if score != nil {
 816		variables["score"] = *score
 817	}
 818	if startedAt != nil {
 819		if startedAt.Year == 0 && startedAt.Month == 0 && startedAt.Day == 0 {
 820			variables["startedAt"] = nil
 821		} else {
 822			variables["startedAt"] = map[string]int{
 823				"year":  startedAt.Year,
 824				"month": startedAt.Month,
 825				"day":   startedAt.Day,
 826			}
 827		}
 828	}
 829	if completedAt != nil {
 830		if completedAt.Year == 0 && completedAt.Month == 0 && completedAt.Day == 0 {
 831			variables["completedAt"] = nil
 832		} else {
 833			variables["completedAt"] = map[string]int{
 834				"year":  completedAt.Year,
 835				"month": completedAt.Month,
 836				"day":   completedAt.Day,
 837			}
 838		}
 839	}
 840
 841	headers := map[string]string{
 842		"Authorization": "Bearer " + token,
 843		"Content-Type":  "application/json",
 844	}
 845
 846	_, err := makePostRequest(url, query, variables, headers)
 847	if err != nil {
 848		return err
 849	}
 850	return nil
 851}
 852
 853func CompleteAniListAnimeRewatch(token string, anime Anime) error {
 854	status := "COMPLETED"
 855	progress := anime.Ep.Number
 856	repeat := anime.Repeat + 1
 857	completedAt := currentFuzzyDate()
 858	startedAt := anime.StartedAt
 859	if startedAt == (FuzzyDate{}) {
 860		startedAt = completedAt
 861	}
 862	return SaveAniListAnimeListEntry(token, anime.AnilistId, &status, &progress, &repeat, nil, &startedAt, &completedAt)
 863}
 864
 865// Function to rate an anime on AniList
 866func RateAniListAnime(token string, mediaID int) error {
 867	score, err := promptAnimeScoreValue()
 868	if err != nil {
 869		return err
 870	}
 871	return saveAniListAnimeScore(token, mediaID, score)
 872}
 873
 874func saveAniListAnimeScore(token string, mediaID int, score float64) error {
 875	url := "https://graphql.anilist.co"
 876	query := `
 877	mutation($mediaId: Int, $score: Float) {
 878		SaveMediaListEntry(mediaId: $mediaId, score: $score) {
 879			id
 880			mediaId
 881			score
 882		}
 883	}`
 884
 885	variables := map[string]interface{}{
 886		"mediaId": mediaID,
 887		"score":   score,
 888	}
 889
 890	headers := map[string]string{
 891		"Authorization": "Bearer " + token,
 892		"Content-Type":  "application/json",
 893	}
 894
 895	_, err := makePostRequest(url, query, variables, headers)
 896	if err != nil {
 897		return err
 898	}
 899
 900	CurdOut(fmt.Sprintf("Successfully rated anime (mediaId: %d) with score: %.2f", mediaID, score))
 901	return nil
 902}
 903
 904func aniListRetryDelay(resp *http.Response, attempt int) time.Duration {
 905	if resp != nil {
 906		if retryAfter := strings.TrimSpace(resp.Header.Get("Retry-After")); retryAfter != "" {
 907			if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds > 0 {
 908				return time.Duration(seconds) * time.Second
 909			}
 910		}
 911	}
 912
 913	return time.Duration(attempt+1) * 2 * time.Second
 914}
 915
 916// Helper function to make POST requests
 917func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) {
 918	requestBody, err := json.Marshal(map[string]interface{}{
 919		"query":     query,
 920		"variables": variables,
 921	})
 922	if err != nil {
 923		return nil, fmt.Errorf("failed to marshal request body: %w", err)
 924	}
 925
 926	token := ""
 927	if headers != nil {
 928		if authHeader := headers["Authorization"]; strings.HasPrefix(authHeader, "Bearer ") {
 929			token = strings.TrimPrefix(authHeader, "Bearer ")
 930		}
 931	}
 932
 933	for authAttempt := 0; authAttempt < 2; authAttempt++ {
 934		response, err := makePostRequestAttempt(url, requestBody, headers)
 935		if err == nil {
 936			return response, nil
 937		}
 938		if authAttempt == 0 && isInvalidTokenError(err) && token != "" {
 939			newToken, renewed, renewErr := tryRenewAniListTokenForAPI(token, "invalid token")
 940			if renewErr != nil {
 941				return nil, renewErr
 942			}
 943			if renewed {
 944				token = newToken
 945				if headers == nil {
 946					headers = map[string]string{}
 947				}
 948				headers["Authorization"] = "Bearer " + newToken
 949				continue
 950			}
 951		}
 952		return nil, err
 953	}
 954
 955	return nil, fmt.Errorf("AniList request failed after token renewal")
 956}
 957
 958func makePostRequestAttempt(url string, requestBody []byte, headers map[string]string) (map[string]interface{}, error) {
 959	client := sharedHTTPClient
 960	if client == nil {
 961		client = &http.Client{Timeout: 15 * time.Second}
 962	}
 963	for attempt := 0; attempt < 5; attempt++ {
 964		req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
 965		if err != nil {
 966			return nil, fmt.Errorf("failed to create request: %w", err)
 967		}
 968
 969		req.Header.Set("Content-Type", "application/json")
 970		for key, value := range headers {
 971			req.Header.Set(key, value)
 972		}
 973
 974		resp, err := client.Do(req)
 975		if err != nil {
 976			return nil, fmt.Errorf("failed to send request: %w", err)
 977		}
 978
 979		body, readErr := io.ReadAll(resp.Body)
 980		resp.Body.Close()
 981		if readErr != nil {
 982			return nil, fmt.Errorf("failed to read response body: %w", readErr)
 983		}
 984
 985		if resp.StatusCode == http.StatusTooManyRequests {
 986			if attempt == 4 {
 987				return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
 988			}
 989			time.Sleep(aniListRetryDelay(resp, attempt))
 990			continue
 991		}
 992		if resp.StatusCode != http.StatusOK {
 993			return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
 994		}
 995
 996		var responseData map[string]interface{}
 997		if err := json.Unmarshal(body, &responseData); err != nil {
 998			return nil, fmt.Errorf("failed to unmarshal response: %w", err)
 999		}
1000		if rawErrors, exists := responseData["errors"]; exists {
1001			errorBody, _ := json.Marshal(rawErrors)
1002			return nil, fmt.Errorf("graphql errors: %s", strings.TrimSpace(string(errorBody)))
1003		}
1004
1005		return responseData, nil
1006	}
1007
1008	return nil, fmt.Errorf("AniList request failed after retries")
1009}
1010
1011// isAniListCustomList reports whether a MediaListCollection list is a user custom
1012// list. Custom lists re-export entries that already appear under status lists, so
1013// including them double-counts the same media in Show All / CURRENT.
1014func isAniListCustomList(listData map[string]interface{}) bool {
1015	if listData == nil {
1016		return false
1017	}
1018	if isCustom, ok := listData["isCustomList"].(bool); ok {
1019		return isCustom
1020	}
1021	return false
1022}
1023
1024// dedupeEntriesByMediaID keeps the first occurrence of each non-zero Media.ID.
1025func dedupeEntriesByMediaID(entries []Entry) []Entry {
1026	if len(entries) < 2 {
1027		return entries
1028	}
1029	seen := make(map[int]struct{}, len(entries))
1030	out := make([]Entry, 0, len(entries))
1031	for _, entry := range entries {
1032		id := entry.Media.ID
1033		if id != 0 {
1034			if _, exists := seen[id]; exists {
1035				continue
1036			}
1037			seen[id] = struct{}{}
1038		}
1039		out = append(out, entry)
1040	}
1041	return out
1042}
1043
1044func ParseAnimeList(input map[string]interface{}) AnimeList {
1045	var animeList AnimeList
1046
1047	toInt := func(value interface{}) int {
1048		switch v := value.(type) {
1049		case int:
1050			return v
1051		case float64:
1052			return int(v) // You could also use int(math.Round(v)) to round
1053		default:
1054			return 0 // Default value for unexpected types
1055		}
1056	}
1057
1058	safeString := func(value interface{}) string {
1059		if value == nil {
1060			return ""
1061		}
1062
1063		// Attempt to assert the value as a string
1064		if str, ok := value.(string); ok {
1065			return str
1066		}
1067
1068		// If it's not a string, return an empty string or handle it as needed
1069		return ""
1070	}
1071
1072	parseFuzzyDate := func(value interface{}) FuzzyDate {
1073		dateMap, ok := value.(map[string]interface{})
1074		if !ok || dateMap == nil {
1075			return FuzzyDate{}
1076		}
1077
1078		return FuzzyDate{
1079			Year:  toInt(dateMap["year"]),
1080			Month: toInt(dateMap["month"]),
1081			Day:   toInt(dateMap["day"]),
1082		}
1083	}
1084
1085	if input == nil {
1086		Log("AniList response is nil")
1087		return animeList
1088	}
1089
1090	// Access the list entries in the input map
1091	if input["data"] == nil {
1092		Log("Anilist request failed")
1093		return animeList
1094	}
1095	data, ok := input["data"].(map[string]interface{})
1096	if !ok {
1097		Log("AniList response data field is invalid")
1098		return animeList
1099	}
1100	collection, ok := data["MediaListCollection"].(map[string]interface{})
1101	if !ok {
1102		Log("AniList response MediaListCollection field is invalid")
1103		return animeList
1104	}
1105	mediaList, ok := collection["lists"].([]interface{})
1106	if !ok {
1107		Log("AniList response lists field is invalid")
1108		return animeList
1109	}
1110
1111	// Prefer status lists; custom lists re-export the same MediaList entries.
1112	seenMediaIDs := make(map[int]struct{})
1113
1114	for _, list := range mediaList {
1115		listData, ok := list.(map[string]interface{})
1116		if !ok {
1117			continue
1118		}
1119		if isAniListCustomList(listData) {
1120			continue
1121		}
1122		entries, ok := listData["entries"].([]interface{})
1123		if !ok {
1124			continue
1125		}
1126
1127		for _, entry := range entries {
1128			entryData, ok := entry.(map[string]interface{})
1129			if !ok {
1130				continue
1131			}
1132			media, ok := entryData["media"].(map[string]interface{})
1133			if !ok {
1134				continue
1135			}
1136			title, _ := media["title"].(map[string]interface{})
1137			animeEntry := Entry{
1138				ListID: toInt(entryData["id"]),
1139				Media: Media{
1140					Duration: toInt(media["duration"]),
1141					Episodes: toInt(media["episodes"]),
1142					Format:   safeString(media["format"]),
1143					ID:       toInt(media["id"]),
1144					MalID:    toInt(media["idMal"]),
1145					Title: AnimeTitle{
1146						English:  safeString(title["english"]),
1147						Romaji:   safeString(title["romaji"]),
1148						Japanese: safeString(title["native"]),
1149					},
1150					Status: safeString(media["status"]),
1151				},
1152				Progress:    toInt(entryData["progress"]),
1153				Repeat:      toInt(entryData["repeat"]),
1154				Status:      safeString(entryData["status"]), // Ensure status is fetched safely
1155				StartedAt:   parseFuzzyDate(entryData["startedAt"]),
1156				CompletedAt: parseFuzzyDate(entryData["completedAt"]),
1157				UpdatedAt:   time.Unix(int64(toInt(entryData["updatedAt"])), 0).UTC(),
1158			}
1159			if score, ok := entryData["score"].(float64); ok {
1160				animeEntry.Score = score
1161			}
1162
1163			if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
1164				animeEntry.CoverImage = safeString(coverImage["large"])
1165			}
1166
1167			// Defense in depth: never insert the same media twice even if AniList
1168			// returns the entry under multiple non-custom lists.
1169			if animeEntry.Media.ID != 0 {
1170				if _, exists := seenMediaIDs[animeEntry.Media.ID]; exists {
1171					continue
1172				}
1173				seenMediaIDs[animeEntry.Media.ID] = struct{}{}
1174			}
1175
1176			// Append entries based on their status
1177			switch animeEntry.Status {
1178			case "CURRENT":
1179				animeList.Watching = append(animeList.Watching, animeEntry)
1180			case "COMPLETED":
1181				animeList.Completed = append(animeList.Completed, animeEntry)
1182			case "PAUSED":
1183				animeList.Paused = append(animeList.Paused, animeEntry)
1184			case "DROPPED":
1185				animeList.Dropped = append(animeList.Dropped, animeEntry)
1186			case "PLANNING":
1187				animeList.Planning = append(animeList.Planning, animeEntry)
1188			case "REPEATING": // Anilist uses REPEATING for rewatching
1189				animeList.Rewatching = append(animeList.Rewatching, animeEntry)
1190			}
1191		}
1192	}
1193
1194	return animeList
1195}
1196
1197// FindAnimeByID searches for an anime by its ID in the AnimeList
1198func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
1199	id, err := strconv.Atoi(idStr)
1200	if err != nil {
1201		return nil, fmt.Errorf("invalid ID format: %s", idStr)
1202	}
1203
1204	// Define a slice of pointers to hold categories
1205	categories := [][]Entry{
1206		list.Watching,
1207		list.Completed,
1208		list.Paused,
1209		list.Dropped,
1210		list.Planning,
1211		list.Rewatching, // Add Rewatching list
1212	}
1213
1214	// Iterate through each category
1215	for _, category := range categories {
1216		for _, entry := range category {
1217			if entry.Media.ID == id {
1218				return &entry, nil // Return a pointer to the found entry
1219			}
1220		}
1221	}
1222
1223	return nil, fmt.Errorf("anime with ID %d not found", id) // Return an error if not found
1224}
1225
1226// FindAnimeByAnilistIDInAnimes searches for an anime by its AniList ID in a slice of Anime
1227func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error) {
1228	for i := range animes {
1229		if animes[i].AnilistId == anilistID {
1230			return &animes[i], nil
1231		}
1232	}
1233	return nil, fmt.Errorf("anime with ID %d not found", anilistID)
1234}
1235
1236// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token
1237func GetAnimeDataByID(id int, token string) (Anime, error) {
1238	url := "https://graphql.anilist.co"
1239	query := `
1240	query ($id: Int) {
1241		Media(id: $id, type: ANIME) {
1242			id
1243			idMal
1244			episodes
1245			duration
1246			status
1247			title {
1248				romaji
1249				english
1250				native
1251			}
1252			coverImage {
1253				large
1254			}
1255			nextAiringEpisode {
1256				episode
1257			}
1258		}
1259	}`
1260
1261	variables := map[string]interface{}{
1262		"id": id,
1263	}
1264
1265	headers := map[string]string{"Content-Type": "application/json"}
1266	if token != "" {
1267		headers["Authorization"] = "Bearer " + token
1268	}
1269
1270	response, err := makePostRequest(url, query, variables, headers)
1271	if err != nil {
1272		return Anime{}, fmt.Errorf("failed to get anime data: %w", err)
1273	}
1274
1275	data, ok := response["data"].(map[string]interface{})
1276	if !ok {
1277		return Anime{}, fmt.Errorf("invalid response format: data field missing")
1278	}
1279
1280	media, ok := data["Media"].(map[string]interface{})
1281	if !ok {
1282		return Anime{}, fmt.Errorf("invalid response format: Media field missing")
1283	}
1284
1285	anime := Anime{
1286		AnilistId: id,
1287		IsAiring:  false,
1288	}
1289
1290	if malID, ok := media["idMal"].(float64); ok {
1291		anime.MalId = int(malID)
1292	}
1293
1294	// Safely handle episodes field which might be nil for currently airing shows
1295	if episodes, ok := media["episodes"].(float64); ok {
1296		anime.TotalEpisodes = int(episodes)
1297	}
1298	if duration, ok := media["duration"].(float64); ok {
1299		anime.Ep.Duration = int(duration) * 60
1300	}
1301	if title, ok := media["title"].(map[string]interface{}); ok {
1302		anime.Title = AnimeTitle{
1303			Romaji:   safeAniListString(title["romaji"]),
1304			English:  safeAniListString(title["english"]),
1305			Japanese: safeAniListString(title["native"]),
1306		}
1307	}
1308	if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
1309		anime.CoverImage = safeAniListString(coverImage["large"])
1310	}
1311
1312	// Check status
1313	if status, ok := media["status"].(string); ok {
1314		anime.IsAiring = status == "RELEASING"
1315	}
1316
1317	// Double check with nextAiringEpisode
1318	if nextEp, ok := media["nextAiringEpisode"].(map[string]interface{}); ok && nextEp != nil {
1319		anime.IsAiring = true
1320	}
1321
1322	return anime, nil
1323}
1324
1325// SequelInfo holds information about a sequel anime
1326type SequelInfo struct {
1327	ID         int
1328	Title      AnimeTitle
1329	CoverImage string
1330	Episodes   int
1331	Status     string // "FINISHED", "RELEASING", "NOT_YET_RELEASED"
1332	SiteURL    string
1333}
1334
1335// GetAnimeSequel fetches sequel information for a given anime from AniList
1336// GetAnimeSequel fetches sequel information for a given anime from AniList
1337func GetAnimeSequel(animeID int, token string) ([]SequelInfo, error) {
1338	url := "https://graphql.anilist.co"
1339	query := `
1340	query ($id: Int) {
1341		Media(id: $id, type: ANIME) {
1342			relations {
1343				edges {
1344					relationType
1345					node {
1346						id
1347						title {
1348							romaji
1349							english
1350						}
1351						coverImage {
1352							large
1353						}
1354						episodes
1355						status
1356						siteUrl
1357					}
1358				}
1359			}
1360		}
1361	}`
1362
1363	variables := map[string]interface{}{
1364		"id": animeID,
1365	}
1366
1367	headers := map[string]string{"Content-Type": "application/json"}
1368	if token != "" {
1369		headers["Authorization"] = "Bearer " + token
1370	}
1371
1372	response, err := makePostRequest(url, query, variables, headers)
1373	if err != nil {
1374		return nil, fmt.Errorf("failed to get anime relations: %w", err)
1375	}
1376
1377	data, ok := response["data"].(map[string]interface{})
1378	if !ok {
1379		return nil, fmt.Errorf("invalid response format: data field missing")
1380	}
1381
1382	media, ok := data["Media"].(map[string]interface{})
1383	if !ok {
1384		return nil, fmt.Errorf("invalid response format: Media field missing")
1385	}
1386
1387	relations, ok := media["relations"].(map[string]interface{})
1388	if !ok {
1389		return nil, nil // No relations found
1390	}
1391
1392	edges, ok := relations["edges"].([]interface{})
1393	if !ok || len(edges) == 0 {
1394		return nil, nil // No edges found
1395	}
1396
1397	var sequels []SequelInfo
1398
1399	// Look for a SEQUEL relation
1400	for _, edge := range edges {
1401		edgeData, ok := edge.(map[string]interface{})
1402		if !ok {
1403			continue
1404		}
1405
1406		relationType, ok := edgeData["relationType"].(string)
1407		if !ok || relationType != "SEQUEL" {
1408			continue
1409		}
1410
1411		node, ok := edgeData["node"].(map[string]interface{})
1412		if !ok {
1413			continue
1414		}
1415
1416		var sequel SequelInfo
1417
1418		// Parse ID
1419		if id, ok := node["id"].(float64); ok {
1420			sequel.ID = int(id)
1421		}
1422
1423		// Parse title
1424		if title, ok := node["title"].(map[string]interface{}); ok {
1425			if romaji, ok := title["romaji"].(string); ok {
1426				sequel.Title.Romaji = romaji
1427			}
1428			if english, ok := title["english"].(string); ok {
1429				sequel.Title.English = english
1430			}
1431		}
1432
1433		// Parse cover image
1434		if coverImage, ok := node["coverImage"].(map[string]interface{}); ok {
1435			if large, ok := coverImage["large"].(string); ok {
1436				sequel.CoverImage = large
1437			}
1438		}
1439
1440		// Parse episodes
1441		if episodes, ok := node["episodes"].(float64); ok {
1442			sequel.Episodes = int(episodes)
1443		}
1444
1445		// Parse status
1446		if status, ok := node["status"].(string); ok {
1447			sequel.Status = status
1448		}
1449
1450		// Parse siteUrl
1451		if siteUrl, ok := node["siteUrl"].(string); ok {
1452			sequel.SiteURL = siteUrl
1453		}
1454
1455		sequels = append(sequels, sequel)
1456	}
1457
1458	if len(sequels) == 0 {
1459		return nil, nil // No sequel found
1460	}
1461
1462	return sequels, nil
1463}
1464
1465// AddAnimeToList adds an anime to a specified list (CURRENT, PLANNING, PAUSED, DROPPED)
1466func AddAniListAnimeToList(animeID int, status string, token string) error {
1467	url := "https://graphql.anilist.co"
1468	mutation := `
1469	mutation ($mediaId: Int, $status: MediaListStatus) {
1470		SaveMediaListEntry (mediaId: $mediaId, status: $status) {
1471			id
1472			status
1473		}
1474	}`
1475
1476	variables := map[string]interface{}{
1477		"mediaId": animeID,
1478		"status":  status,
1479	}
1480
1481	headers := map[string]string{
1482		"Authorization": "Bearer " + token,
1483		"Content-Type":  "application/json",
1484	}
1485
1486	_, err := makePostRequest(url, mutation, variables, headers)
1487	if err != nil {
1488		return fmt.Errorf("failed to add anime to list: %w", err)
1489	}
1490
1491	statusMap := map[string]string{
1492		"CURRENT":   "Currently Watching",
1493		"COMPLETED": "Completed",
1494		"PAUSED":    "On Hold",
1495		"DROPPED":   "Dropped",
1496		"PLANNING":  "Plan to Watch",
1497		"REPEATING": "Rewatching",
1498	}
1499
1500	CurdOut(fmt.Sprintf("Anime added to: %s", statusMap[status]))
1501	return nil
1502}
1503
1504func DeleteAniListListEntry(token string, listID int) error {
1505	url := "https://graphql.anilist.co"
1506	query := `
1507	mutation ($id: Int) {
1508		DeleteMediaListEntry(id: $id) {
1509			deleted
1510		}
1511	}`
1512
1513	headers := map[string]string{"Content-Type": "application/json"}
1514	if token != "" {
1515		headers["Authorization"] = "Bearer " + token
1516	}
1517
1518	_, err := makePostRequest(url, query, map[string]interface{}{"id": listID}, headers)
1519	return err
1520}
1521
1522// FindSequelInAnimeList searches for a sequel in the user's anime list and returns its status
1523func FindSequelInAnimeList(list AnimeList, sequelID int) (string, bool) {
1524	// Check all categories
1525	for _, entry := range list.Watching {
1526		if entry.Media.ID == sequelID {
1527			return "CURRENT", true
1528		}
1529	}
1530	for _, entry := range list.Planning {
1531		if entry.Media.ID == sequelID {
1532			return "PLANNING", true
1533		}
1534	}
1535	for _, entry := range list.Completed {
1536		if entry.Media.ID == sequelID {
1537			return "COMPLETED", true
1538		}
1539	}
1540	for _, entry := range list.Paused {
1541		if entry.Media.ID == sequelID {
1542			return "PAUSED", true
1543		}
1544	}
1545	for _, entry := range list.Dropped {
1546		if entry.Media.ID == sequelID {
1547			return "DROPPED", true
1548		}
1549	}
1550	for _, entry := range list.Rewatching {
1551		if entry.Media.ID == sequelID {
1552			return "REWATCHING", true
1553		}
1554	}
1555
1556	return "", false
1557}