internal/anilist.go

907 lines · 22852 bytes

  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)
 15
 16// FindKeyByValue searches for a key associated with a given value in a map[string]string
 17func FindKeyByValue(m map[string]string, value string) (string, error) {
 18	for key, val := range m {
 19		if val == value {
 20			return key, nil // Return the key and true if the value is found
 21		}
 22	}
 23	return "", fmt.Errorf("no key with value %v", value) // Return empty string and false if the value is not found
 24}
 25
 26// GetAnimeMap takes an AnimeList and returns a map with media.id as key and media.title.english as value.
 27func GetAnimeMap(animeList AnimeList) map[string]string {
 28	animeMap := make(map[string]string)
 29	userCurdConfig := GetGlobalConfig()
 30
 31	// Helper function to populate the map from a slice of entries
 32	populateMap := func(entries []Entry) {
 33		for _, entry := range entries {
 34			// Only include entries with a non-empty English title
 35
 36			if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
 37				animeMap[strconv.Itoa(entry.Media.ID)] = entry.Media.Title.English
 38			} else {
 39				animeMap[strconv.Itoa(entry.Media.ID)] = entry.Media.Title.Romaji
 40			}
 41		}
 42	}
 43
 44	// Populate the map for each category
 45	populateMap(animeList.Watching)
 46	populateMap(animeList.Completed)
 47	populateMap(animeList.Paused)
 48	populateMap(animeList.Dropped)
 49	populateMap(animeList.Planning)
 50
 51	return animeMap
 52}
 53
 54// GetAnimeMapPreview takes an AnimeList and returns a map with media.id as key and media.title.english as value.
 55func GetAnimeMapPreview(animeList AnimeList) map[string]RofiSelectPreview {
 56	userCurdConfig := GetGlobalConfig()
 57	animeMap := make(map[string]RofiSelectPreview)
 58
 59	// Helper function to populate the map from a slice of entries
 60	populateMap := func(entries []Entry) {
 61		for _, entry := range entries {
 62			// Only include entries with a non-empty English title
 63			Log(fmt.Errorf("AnimeNameLanguage: %v", userCurdConfig.AnimeNameLanguage))
 64
 65			if entry.Media.Title.English != "" && userCurdConfig.AnimeNameLanguage == "english" {
 66				animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 67					Title:      entry.Media.Title.English,
 68					CoverImage: entry.CoverImage,
 69				}
 70			} else {
 71				animeMap[strconv.Itoa(entry.Media.ID)] = RofiSelectPreview{
 72					Title:      entry.Media.Title.Romaji,
 73					CoverImage: entry.CoverImage,
 74				}
 75			}
 76		}
 77	}
 78
 79	// Populate the map for each category
 80	populateMap(animeList.Watching)
 81	populateMap(animeList.Completed)
 82	populateMap(animeList.Paused)
 83	populateMap(animeList.Dropped)
 84	populateMap(animeList.Planning)
 85
 86	return animeMap
 87}
 88
 89// fuzzy matching w/ Levenshtein distance
 90func levenshtein(a, b string) int {
 91	a = strings.ToLower(a)
 92	b = strings.ToLower(b)
 93	ar, br := []rune(a), []rune(b)
 94	alen, blen := len(ar), len(br)
 95	if alen == 0 {
 96		return blen
 97	}
 98	if blen == 0 {
 99		return alen
100	}
101	matrix := make([][]int, alen+1)
102	for i := range matrix {
103		matrix[i] = make([]int, blen+1)
104	}
105	for i := 0; i <= alen; i++ {
106		matrix[i][0] = i
107	}
108	for j := 0; j <= blen; j++ {
109		matrix[0][j] = j
110	}
111	for i := 1; i <= alen; i++ {
112		for j := 1; j <= blen; j++ {
113			cost := 0
114			if ar[i-1] != br[j-1] {
115				cost = 1
116			}
117			matrix[i][j] = min3(
118				matrix[i-1][j]+1,
119				matrix[i][j-1]+1,
120				matrix[i-1][j-1]+cost,
121			)
122		}
123	}
124	return matrix[alen][blen]
125}
126
127func min3(a, b, c int) int {
128	if a < b && a < c {
129		return a
130	}
131	if b < c {
132		return b
133	}
134	return c
135}
136
137// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
138func SearchAnimeAnilistPreview(query, token string) (map[string]RofiSelectPreview, error) {
139	url := "https://graphql.anilist.co"
140
141	queryString := `
142	query ($search: String) {
143		Page(page: 1, perPage: 50) {
144			media(search: $search, type: ANIME) {
145				id
146				title {
147					romaji
148					english
149					native
150				}
151				coverImage {
152					large
153				}
154			}
155		}
156	}`
157
158	variables := map[string]string{"search": query}
159	requestBody, err := json.Marshal(map[string]interface{}{
160		"query":     queryString,
161		"variables": variables,
162	})
163	if err != nil {
164		return nil, fmt.Errorf("failed to marshal request body: %w", err)
165	}
166
167	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
168	if err != nil {
169		return nil, fmt.Errorf("failed to create new request: %w", err)
170	}
171
172	req.Header.Set("Authorization", "Bearer "+token)
173	req.Header.Set("Content-Type", "application/json")
174
175	client := &http.Client{}
176	resp, err := client.Do(req)
177	if err != nil {
178		return nil, fmt.Errorf("failed to make request: %w", err)
179	}
180	defer resp.Body.Close()
181
182	if resp.StatusCode != http.StatusOK {
183		body, _ := io.ReadAll(resp.Body)
184		return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body))
185	}
186
187	body, err := io.ReadAll(resp.Body)
188	if err != nil {
189		return nil, fmt.Errorf("failed to read response body: %w", err)
190	}
191
192	var responseData map[string]ResponseData
193	err = json.Unmarshal(body, &responseData)
194	if err != nil {
195		return nil, fmt.Errorf("failed to unmarshal response: %w", err)
196	}
197
198	animeList := responseData["data"].Page.Media
199	animeDict := make(map[string]RofiSelectPreview)
200
201	type scoredAnime struct {
202		id    string
203		title string
204		cover string
205		score int
206	}
207	var scored []scoredAnime
208	for _, anime := range animeList {
209		idStr := strconv.Itoa(anime.ID)
210		title := anime.Title.English
211		if title == "" {
212			title = anime.Title.Romaji
213		}
214		cover := anime.CoverImage.Large
215		score := levenshtein(title, query)
216		scored = append(scored, scoredAnime{idStr, title, cover, score})
217	}
218	sort.Slice(scored, func(i, j int) bool {
219		return scored[i].score < scored[j].score
220	})
221	for i, s := range scored {
222		if i >= 10 {
223			break
224		}
225		animeDict[s.id] = RofiSelectPreview{
226			Title:      s.title,
227			CoverImage: s.cover,
228		}
229	}
230	return animeDict, nil
231}
232
233// SearchAnimeAnilist sends the query to AniList and returns a map of title to ID
234func SearchAnimeAnilist(query, token string) ([]SelectionOption, error) {
235	url := "https://graphql.anilist.co"
236
237	queryString := `
238	query ($search: String) {
239		Page(page: 1, perPage: 50) {
240			media(search: $search, type: ANIME) {
241				id
242				title {
243					romaji
244					english
245					native
246				}
247			}
248		}
249	}`
250
251	variables := map[string]string{"search": query}
252	requestBody, err := json.Marshal(map[string]interface{}{
253		"query":     queryString,
254		"variables": variables,
255	})
256	if err != nil {
257		return nil, fmt.Errorf("failed to marshal request body: %w", err)
258	}
259
260	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
261	if err != nil {
262		return nil, fmt.Errorf("failed to create new request: %w", err)
263	}
264
265	req.Header.Set("Authorization", "Bearer "+token)
266	req.Header.Set("Content-Type", "application/json")
267
268	client := &http.Client{}
269	resp, err := client.Do(req)
270	if err != nil {
271		return nil, fmt.Errorf("failed to make request: %w", err)
272	}
273	defer resp.Body.Close()
274
275	if resp.StatusCode != http.StatusOK {
276		body, _ := io.ReadAll(resp.Body)
277		return nil, fmt.Errorf("failed to search for anime. Status Code: %d, Response: %s", resp.StatusCode, string(body))
278	}
279
280	body, err := io.ReadAll(resp.Body)
281	if err != nil {
282		return nil, fmt.Errorf("failed to read response body: %w", err)
283	}
284
285	var responseData map[string]ResponseData
286	err = json.Unmarshal(body, &responseData)
287	if err != nil {
288		return nil, fmt.Errorf("failed to unmarshal response: %w", err)
289	}
290
291	animeList := responseData["data"].Page.Media
292	var results []SelectionOption
293
294	type scoredAnime struct {
295		id    string
296		title string
297		score int
298	}
299	var scored []scoredAnime
300	for _, anime := range animeList {
301		idStr := strconv.Itoa(anime.ID)
302		title := anime.Title.English
303		if title == "" {
304			title = anime.Title.Romaji
305		}
306		score := levenshtein(title, query)
307		scored = append(scored, scoredAnime{idStr, title, score})
308	}
309	sort.Slice(scored, func(i, j int) bool {
310		return scored[i].score < scored[j].score
311	})
312	for i, s := range scored {
313		if i >= 10 {
314			break
315		}
316		results = append(results, SelectionOption{
317			Key:   s.id,
318			Label: s.title,
319		})
320	}
321	return results, nil
322}
323
324// Function to get AniList user ID and username
325func GetAnilistUserID(token string) (int, string, error) {
326	url := "https://graphql.anilist.co"
327	query := `
328	query {
329		Viewer {
330			id
331			name
332		}
333	}`
334
335	headers := map[string]string{
336		"Authorization": "Bearer " + token,
337		"Content-Type":  "application/json",
338		"Accept":        "application/json",
339	}
340
341	response, err := makePostRequest(url, query, nil, headers)
342	if err != nil {
343		return 0, "", err
344	}
345
346	data := response["data"].(map[string]interface{})["Viewer"].(map[string]interface{})
347	userID := int(data["id"].(float64))
348	userName := data["name"].(string)
349
350	return userID, userName, nil
351}
352
353// Function to add an anime to the watching list
354func AddAnimeToWatchingList(animeID int, token string) error {
355	url := "https://graphql.anilist.co"
356	mutation := `
357	mutation ($mediaId: Int) {
358		SaveMediaListEntry (mediaId: $mediaId, status: CURRENT) {
359			id
360			status
361		}
362	}`
363
364	variables := map[string]interface{}{
365		"mediaId": animeID,
366	}
367
368	headers := map[string]string{
369		"Authorization": "Bearer " + token,
370		"Content-Type":  "application/json",
371	}
372
373	_, err := makePostRequest(url, mutation, variables, headers)
374	if err != nil {
375		return fmt.Errorf("failed to add anime: %w", err)
376	}
377
378	CurdOut(fmt.Sprintf("Anime with ID %d has been added to your watching list.", animeID))
379	return nil
380}
381
382// Function to get MAL ID using AniList media ID
383func GetAnimeMalID(anilistMediaID int) (int, error) {
384	url := "https://graphql.anilist.co"
385	query := `
386	query ($id: Int) {
387		Media(id: $id) {
388			idMal
389		}
390	}`
391
392	variables := map[string]interface{}{
393		"id": anilistMediaID,
394	}
395
396	response, err := makePostRequest(url, query, variables, nil)
397	if err != nil {
398		return 0, err
399	}
400
401	malID := int(response["data"].(map[string]interface{})["Media"].(map[string]interface{})["idMal"].(float64))
402	return malID, nil
403}
404
405// This function retrieves the MAL ID and cover image URL for an anime from AniList
406func GetAnimeIDAndImage(anilistMediaID int) (int, string, error) {
407	url := "https://graphql.anilist.co"
408	query := `
409	query ($id: Int) {
410		Media(id: $id) {
411			coverImage {
412				large
413			}
414			idMal
415		}
416	}`
417
418	variables := map[string]interface{}{
419		"id": anilistMediaID,
420	}
421
422	response, err := makePostRequest(url, query, variables, nil)
423	if err != nil {
424		return 0, "", err
425	}
426
427	data := response["data"].(map[string]interface{})["Media"].(map[string]interface{})
428	malID := int(data["idMal"].(float64))
429	imageURL := data["coverImage"].(map[string]interface{})["large"].(string)
430
431	return malID, imageURL, nil
432}
433
434// Function to get user data from AniList
435func GetUserData(token string, userID int) (map[string]interface{}, error) {
436	query := fmt.Sprintf(`
437	{
438		MediaListCollection(userId: %d, type: ANIME) {
439			lists {
440				entries {
441					media {
442						id
443						episodes
444						duration
445						title {
446							romaji
447							english
448							native
449						}
450					}
451					status
452					score
453					progress
454				}
455			}
456		}
457	}`, userID)
458
459	headers := map[string]string{
460		"Authorization": "Bearer " + token,
461		"Content-Type":  "application/json",
462	}
463
464	response, err := makePostRequest("https://graphql.anilist.co", query, nil, headers)
465	if err != nil {
466		return nil, err
467	}
468
469	return response, nil
470}
471
472func GetUserDataPreview(token string, userID int) (map[string]interface{}, error) {
473	query := fmt.Sprintf(`
474	{
475		MediaListCollection(userId: %d, type: ANIME) {
476			lists {
477				entries {
478					media {
479						id
480						episodes
481						duration
482						coverImage {
483							large
484						}
485						title {
486							romaji
487							english
488							native
489						}
490					}
491					status
492					score
493					progress
494				}
495			}
496		}
497	}`, userID)
498
499	headers := map[string]string{
500		"Authorization": "Bearer " + token,
501		"Content-Type":  "application/json",
502	}
503
504	response, err := makePostRequest("https://graphql.anilist.co", query, nil, headers)
505	if err != nil {
506		return nil, err
507	}
508
509	return response, nil
510}
511
512// Function to load a JSON file
513func LoadJSONFile(filePath string) (map[string]interface{}, error) {
514	data, err := os.ReadFile(filepath.Clean(filePath))
515	if err != nil {
516		return nil, fmt.Errorf("failed to read file: %w", err)
517	}
518
519	var jsonData map[string]interface{}
520	err = json.Unmarshal(data, &jsonData)
521	if err != nil {
522		return nil, fmt.Errorf("failed to parse JSON: %w", err)
523	}
524
525	return jsonData, nil
526}
527
528// Function to search for an anime by title in user data
529func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []map[string]interface{} {
530	results := []map[string]interface{}{}
531
532	lists := jsonData["data"].(map[string]interface{})["MediaListCollection"].(map[string]interface{})["lists"].([]interface{})
533	for _, list := range lists {
534		entries := list.(map[string]interface{})["entries"].([]interface{})
535		for _, entry := range entries {
536			media := entry.(map[string]interface{})["media"].(map[string]interface{})
537			romajiTitle := media["title"].(map[string]interface{})["romaji"].(string)
538			englishTitle := media["title"].(map[string]interface{})["english"].(string)
539			episodes := int(media["episodes"].(float64))
540			duration := int(media["duration"].(float64))
541
542			if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) {
543				result := map[string]interface{}{
544					"id":            media["id"],
545					"progress":      entry.(map[string]interface{})["progress"],
546					"romaji_title":  romajiTitle,
547					"english_title": englishTitle,
548					"episodes":      episodes,
549					"duration":      duration,
550				}
551				results = append(results, result)
552			}
553		}
554	}
555
556	return results
557}
558
559// Function to update anime progress
560func UpdateAnimeProgress(token string, mediaID, progress int) error {
561	url := "https://graphql.anilist.co"
562	query := `
563	mutation($mediaId: Int, $progress: Int) {
564		SaveMediaListEntry(mediaId: $mediaId, progress: $progress) {
565			id
566			progress
567		}
568	}`
569
570	variables := map[string]interface{}{
571		"mediaId":  mediaID,
572		"progress": progress,
573	}
574
575	headers := map[string]string{
576		"Authorization": "Bearer " + token,
577		"Content-Type":  "application/json",
578	}
579
580	_, err := makePostRequest(url, query, variables, headers)
581	if err != nil {
582		return err
583	}
584
585	CurdOut(fmt.Sprint("Anime progress updated! Latest watched episode: ", progress))
586	return nil
587}
588
589func UpdateAnimeStatus(token string, mediaID int, status string) error {
590	url := "https://graphql.anilist.co"
591	query := `
592	mutation($mediaId: Int, $status: MediaListStatus) {
593		SaveMediaListEntry(mediaId: $mediaId, status: $status) {
594			id
595			status
596		}
597	}`
598
599	variables := map[string]interface{}{
600		"mediaId": mediaID,
601		"status":  status,
602	}
603
604	headers := map[string]string{
605		"Authorization": "Bearer " + token,
606		"Content-Type":  "application/json",
607	}
608
609	_, err := makePostRequest(url, query, variables, headers)
610	if err != nil {
611		return fmt.Errorf("failed to update anime status: %w", err)
612	}
613
614	statusMap := map[string]string{
615		"CURRENT":   "Currently Watching",
616		"COMPLETED": "Completed",
617		"PAUSED":    "On Hold",
618		"DROPPED":   "Dropped",
619		"PLANNING":  "Plan to Watch",
620	}
621
622	CurdOut(fmt.Sprintf("Anime status updated to: %s", statusMap[status]))
623	return nil
624}
625
626// Function to rate an anime on AniList
627func RateAnime(token string, mediaID int) error {
628	var score float64
629	var err error
630
631	userCurdConfig := GetGlobalConfig()
632	if userCurdConfig == nil {
633		return fmt.Errorf("failed to get curd config")
634	}
635
636	if userCurdConfig.RofiSelection {
637		userInput, err := GetUserInputFromRofi("Enter a score for the anime (0-10)")
638		if err != nil {
639			return err
640		}
641		score, err = strconv.ParseFloat(userInput, 64)
642		if err != nil {
643			return err
644		}
645	} else {
646		fmt.Println("Rate this anime: ")
647		fmt.Scanln(&score)
648	}
649
650	url := "https://graphql.anilist.co"
651	query := `
652	mutation($mediaId: Int, $score: Float) {
653		SaveMediaListEntry(mediaId: $mediaId, score: $score) {
654			id
655			mediaId
656			score
657		}
658	}`
659
660	variables := map[string]interface{}{
661		"mediaId": mediaID,
662		"score":   score,
663	}
664
665	headers := map[string]string{
666		"Authorization": "Bearer " + token,
667		"Content-Type":  "application/json",
668	}
669
670	_, err = makePostRequest(url, query, variables, headers)
671	if err != nil {
672		return err
673	}
674
675	CurdOut(fmt.Sprintf("Successfully rated anime (mediaId: %d) with score: %.2f", mediaID, score))
676	return nil
677}
678
679// Helper function to make POST requests
680func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) {
681	requestBody, err := json.Marshal(map[string]interface{}{
682		"query":     query,
683		"variables": variables,
684	})
685	if err != nil {
686		return nil, fmt.Errorf("failed to marshal request body: %w", err)
687	}
688
689	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
690	if err != nil {
691		return nil, fmt.Errorf("failed to create request: %w", err)
692	}
693
694	req.Header.Set("Content-Type", "application/json") // <-- Important!
695	for key, value := range headers {
696		req.Header.Set(key, value)
697	}
698
699	client := &http.Client{}
700	resp, err := client.Do(req)
701	if err != nil {
702		return nil, fmt.Errorf("failed to send request: %w", err)
703	}
704	defer resp.Body.Close()
705
706	body, err := io.ReadAll(resp.Body)
707	if err != nil {
708		return nil, fmt.Errorf("failed to read response body: %w", err)
709	}
710
711	if resp.StatusCode != http.StatusOK {
712		return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
713	}
714
715	var responseData map[string]interface{}
716	// Unmarshal the response into a map
717	err = json.Unmarshal(body, &responseData)
718	if err != nil {
719		return nil, fmt.Errorf("failed to unmarshal response: %w", err)
720	}
721
722	return responseData, nil
723}
724
725func ParseAnimeList(input map[string]interface{}) AnimeList {
726	var animeList AnimeList
727	userCurdConfig := GetGlobalConfig()
728
729	toInt := func(value interface{}) int {
730		switch v := value.(type) {
731		case int:
732			return v
733		case float64:
734			return int(v) // You could also use int(math.Round(v)) to round
735		default:
736			return 0 // Default value for unexpected types
737		}
738	}
739
740	safeString := func(value interface{}) string {
741		if value == nil {
742			return ""
743		}
744
745		// Attempt to assert the value as a string
746		if str, ok := value.(string); ok {
747			return str
748		}
749
750		// If it's not a string, return an empty string or handle it as needed
751		return ""
752	}
753
754	// Access the list entries in the input map
755	if input["data"] == nil {
756		Log("Anilist request failed")
757		CurdOut("Anilist request failed")
758		ExitCurd(fmt.Errorf("Anilist request failed"))
759		return animeList
760	}
761	data := input["data"].(map[string]interface{})
762	mediaList := data["MediaListCollection"].(map[string]interface{})["lists"].([]interface{})
763
764	for _, list := range mediaList {
765		entries := list.(map[string]interface{})["entries"].([]interface{})
766
767		for _, entry := range entries {
768			entryData := entry.(map[string]interface{})
769			media := entryData["media"].(map[string]interface{})
770			animeEntry := Entry{
771				Media: Media{
772					Duration: toInt(media["duration"]),
773					Episodes: toInt(media["episodes"]),
774					ID:       toInt(media["id"]),
775					Title: AnimeTitle{
776						English:  safeString(media["title"].(map[string]interface{})["english"]),
777						Romaji:   safeString(media["title"].(map[string]interface{})["romaji"]),
778						Japanese: safeString(media["title"].(map[string]interface{})["native"]),
779					},
780				},
781				Progress: toInt(entryData["progress"]),
782				Score:    entryData["score"].(float64),
783				Status:   safeString(entryData["status"]), // Ensure status is fetched safely
784			}
785
786			if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
787				animeEntry.CoverImage = safeString(media["coverImage"].(map[string]interface{})["large"])
788			}
789
790			// Append entries based on their status
791			switch animeEntry.Status {
792			case "CURRENT":
793				animeList.Watching = append(animeList.Watching, animeEntry)
794			case "COMPLETED":
795				animeList.Completed = append(animeList.Completed, animeEntry) // Fix: Ensure Completed list is used
796			case "PAUSED":
797				animeList.Paused = append(animeList.Paused, animeEntry) // Fix: Append to Paused list
798			case "DROPPED":
799				animeList.Dropped = append(animeList.Dropped, animeEntry) // Fix: Append to Dropped list
800			case "PLANNING":
801				animeList.Planning = append(animeList.Planning, animeEntry) // Fix: Append to Planning list
802			}
803		}
804	}
805
806	return animeList
807}
808
809// FindAnimeByID searches for an anime by its ID in the AnimeList
810func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
811	id, err := strconv.Atoi(idStr)
812	if err != nil {
813		return nil, fmt.Errorf("invalid ID format: %s", idStr)
814	}
815
816	// Define a slice of pointers to hold categories
817	categories := [][]Entry{
818		list.Watching,
819		list.Completed,
820		list.Paused,
821		list.Dropped,
822		list.Planning,
823	}
824
825	// Iterate through each category
826	for _, category := range categories {
827		for _, entry := range category {
828			if entry.Media.ID == id {
829				return &entry, nil // Return a pointer to the found entry
830			}
831		}
832	}
833
834	return nil, fmt.Errorf("anime with ID %d not found", id) // Return an error if not found
835}
836
837// FindAnimeByAnilistIDInAnimes searches for an anime by its AniList ID in a slice of Anime
838func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error) {
839	for i := range animes {
840		if animes[i].AnilistId == anilistID {
841			return &animes[i], nil
842		}
843	}
844	return nil, fmt.Errorf("anime with ID %d not found", anilistID)
845}
846
847// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token
848func GetAnimeDataByID(id int, token string) (Anime, error) {
849	url := "https://graphql.anilist.co"
850	query := `
851	query ($id: Int) {
852		Media(id: $id, type: ANIME) {
853			id
854			episodes
855			status
856			nextAiringEpisode {
857				episode
858			}
859		}
860	}`
861
862	variables := map[string]interface{}{
863		"id": id,
864	}
865
866	headers := map[string]string{
867		"Authorization": "Bearer " + token,
868		"Content-Type":  "application/json",
869	}
870
871	response, err := makePostRequest(url, query, variables, headers)
872	if err != nil {
873		return Anime{}, fmt.Errorf("failed to get anime data: %w", err)
874	}
875
876	data, ok := response["data"].(map[string]interface{})
877	if !ok {
878		return Anime{}, fmt.Errorf("invalid response format: data field missing")
879	}
880
881	media, ok := data["Media"].(map[string]interface{})
882	if !ok {
883		return Anime{}, fmt.Errorf("invalid response format: Media field missing")
884	}
885
886	anime := Anime{
887		AnilistId: id,
888		IsAiring:  false,
889	}
890
891	// Safely handle episodes field which might be nil for currently airing shows
892	if episodes, ok := media["episodes"].(float64); ok {
893		anime.TotalEpisodes = int(episodes)
894	}
895
896	// Check status
897	if status, ok := media["status"].(string); ok {
898		anime.IsAiring = status == "RELEASING"
899	}
900
901	// Double check with nextAiringEpisode
902	if nextEp, ok := media["nextAiringEpisode"].(map[string]interface{}); ok && nextEp != nil {
903		anime.IsAiring = true
904	}
905
906	return anime, nil
907}