internal/anilist.go

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