internal/anilist.go

1223 lines · 29956 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 := `
 439	query ($userId: Int, $type: MediaType) {
 440		MediaListCollection(userId: $userId, type: $type) {
 441			lists {
 442				entries {
 443					media {
 444						id
 445						episodes
 446						duration
 447						title {
 448							romaji
 449							english
 450							native
 451						}
 452						status
 453					}
 454					status
 455					score
 456					progress
 457					repeat
 458					startedAt {
 459						year
 460						month
 461						day
 462					}
 463					completedAt {
 464						year
 465						month
 466						day
 467					}
 468				}
 469			}
 470		}
 471	}`
 472
 473	variables := map[string]interface{}{
 474		"userId": userID,
 475		"type":   "ANIME",
 476	}
 477
 478	headers := map[string]string{
 479		"Authorization": "Bearer " + token,
 480		"Content-Type":  "application/json",
 481	}
 482
 483	response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers)
 484	if err != nil {
 485		return nil, err
 486	}
 487
 488	return response, nil
 489}
 490
 491func GetUserDataPreview(token string, userID int) (map[string]interface{}, error) {
 492	query := `
 493	query ($userId: Int, $type: MediaType) {
 494		MediaListCollection(userId: $userId, type: $type) {
 495			lists {
 496				entries {
 497					media {
 498						id
 499						episodes
 500						duration
 501						coverImage {
 502							large
 503						}
 504						title {
 505							romaji
 506							english
 507							native
 508						}
 509						status
 510					}
 511					status
 512					score
 513					progress
 514					repeat
 515					startedAt {
 516						year
 517						month
 518						day
 519					}
 520					completedAt {
 521						year
 522						month
 523						day
 524					}
 525				}
 526			}
 527		}
 528	}`
 529
 530	variables := map[string]interface{}{
 531		"userId": userID,
 532		"type":   "ANIME",
 533	}
 534
 535	headers := map[string]string{
 536		"Authorization": "Bearer " + token,
 537		"Content-Type":  "application/json",
 538	}
 539
 540	response, err := makePostRequest("https://graphql.anilist.co", query, variables, headers)
 541	if err != nil {
 542		return nil, err
 543	}
 544
 545	return response, nil
 546}
 547
 548// Function to load a JSON file
 549func LoadJSONFile(filePath string) (map[string]interface{}, error) {
 550	data, err := os.ReadFile(filepath.Clean(filePath))
 551	if err != nil {
 552		return nil, fmt.Errorf("failed to read file: %w", err)
 553	}
 554
 555	var jsonData map[string]interface{}
 556	err = json.Unmarshal(data, &jsonData)
 557	if err != nil {
 558		return nil, fmt.Errorf("failed to parse JSON: %w", err)
 559	}
 560
 561	return jsonData, nil
 562}
 563
 564// Function to search for an anime by title in user data
 565func SearchAnimeByTitle(jsonData map[string]interface{}, searchTitle string) []map[string]interface{} {
 566	results := []map[string]interface{}{}
 567
 568	lists := jsonData["data"].(map[string]interface{})["MediaListCollection"].(map[string]interface{})["lists"].([]interface{})
 569	for _, list := range lists {
 570		entries := list.(map[string]interface{})["entries"].([]interface{})
 571		for _, entry := range entries {
 572			media := entry.(map[string]interface{})["media"].(map[string]interface{})
 573			romajiTitle := media["title"].(map[string]interface{})["romaji"].(string)
 574			englishTitle := media["title"].(map[string]interface{})["english"].(string)
 575			episodes := int(media["episodes"].(float64))
 576			duration := int(media["duration"].(float64))
 577
 578			if strings.Contains(strings.ToLower(romajiTitle), strings.ToLower(searchTitle)) || strings.Contains(strings.ToLower(englishTitle), strings.ToLower(searchTitle)) {
 579				result := map[string]interface{}{
 580					"id":            media["id"],
 581					"progress":      entry.(map[string]interface{})["progress"],
 582					"romaji_title":  romajiTitle,
 583					"english_title": englishTitle,
 584					"episodes":      episodes,
 585					"duration":      duration,
 586				}
 587				results = append(results, result)
 588			}
 589		}
 590	}
 591
 592	return results
 593}
 594
 595// Function to update anime progress
 596func UpdateAnimeProgress(token string, mediaID, progress int) error {
 597	err := SaveAnimeListEntry(token, mediaID, nil, &progress, nil, nil, nil)
 598	if err != nil {
 599		return err
 600	}
 601
 602	CurdOut(fmt.Sprint("Anime progress updated! Latest watched episode: ", progress))
 603	return nil
 604}
 605
 606func UpdateAnimeStatus(token string, mediaID int, status string) error {
 607	err := SaveAnimeListEntry(token, mediaID, &status, nil, nil, nil, nil)
 608	if err != nil {
 609		return fmt.Errorf("failed to update anime status: %w", err)
 610	}
 611
 612	statusMap := map[string]string{
 613		"CURRENT":   "Currently Watching",
 614		"COMPLETED": "Completed",
 615		"PAUSED":    "On Hold",
 616		"DROPPED":   "Dropped",
 617		"PLANNING":  "Plan to Watch",
 618		"REPEATING": "Rewatching",
 619	}
 620
 621	CurdOut(fmt.Sprintf("Anime status updated to: %s", statusMap[status]))
 622	return nil
 623}
 624
 625func SaveAnimeListEntry(token string, mediaID int, status *string, progress *int, repeat *int, startedAt *FuzzyDate, completedAt *FuzzyDate) error {
 626	url := "https://graphql.anilist.co"
 627	query := `
 628	mutation(
 629		$mediaId: Int
 630		$status: MediaListStatus
 631		$progress: Int
 632		$repeat: Int
 633		$startedAt: FuzzyDateInput
 634		$completedAt: FuzzyDateInput
 635	) {
 636		SaveMediaListEntry(
 637			mediaId: $mediaId
 638			status: $status
 639			progress: $progress
 640			repeat: $repeat
 641			startedAt: $startedAt
 642			completedAt: $completedAt
 643		) {
 644			id
 645			status
 646			progress
 647			repeat
 648			startedAt {
 649				year
 650				month
 651				day
 652			}
 653			completedAt {
 654				year
 655				month
 656				day
 657			}
 658		}
 659	}`
 660
 661	variables := map[string]interface{}{
 662		"mediaId": mediaID,
 663	}
 664	if status != nil {
 665		variables["status"] = *status
 666	}
 667	if progress != nil {
 668		variables["progress"] = *progress
 669	}
 670	if repeat != nil {
 671		variables["repeat"] = *repeat
 672	}
 673	if startedAt != nil && (startedAt.Year != 0 || startedAt.Month != 0 || startedAt.Day != 0) {
 674		variables["startedAt"] = map[string]int{
 675			"year":  startedAt.Year,
 676			"month": startedAt.Month,
 677			"day":   startedAt.Day,
 678		}
 679	}
 680	if completedAt != nil && (completedAt.Year != 0 || completedAt.Month != 0 || completedAt.Day != 0) {
 681		variables["completedAt"] = map[string]int{
 682			"year":  completedAt.Year,
 683			"month": completedAt.Month,
 684			"day":   completedAt.Day,
 685		}
 686	}
 687
 688	headers := map[string]string{
 689		"Authorization": "Bearer " + token,
 690		"Content-Type":  "application/json",
 691	}
 692
 693	_, err := makePostRequest(url, query, variables, headers)
 694	if err != nil {
 695		return err
 696	}
 697	return nil
 698}
 699
 700func CompleteAnimeRewatch(token string, anime Anime) error {
 701	status := "COMPLETED"
 702	repeat := anime.Repeat + 1
 703	return SaveAnimeListEntry(token, anime.AnilistId, &status, nil, &repeat, &anime.StartedAt, &anime.CompletedAt)
 704}
 705
 706// Function to rate an anime on AniList
 707func RateAnime(token string, mediaID int) error {
 708	var score float64
 709	var err error
 710
 711	userCurdConfig := GetGlobalConfig()
 712	if userCurdConfig == nil {
 713		return fmt.Errorf("failed to get curd config")
 714	}
 715
 716	if userCurdConfig.RofiSelection {
 717		userInput, err := GetUserInputFromRofi("Enter a score for the anime (0-10)")
 718		if err != nil {
 719			return err
 720		}
 721		score, err = strconv.ParseFloat(userInput, 64)
 722		if err != nil {
 723			return err
 724		}
 725	} else {
 726		fmt.Println("Rate this anime: ")
 727		fmt.Scanln(&score)
 728	}
 729
 730	url := "https://graphql.anilist.co"
 731	query := `
 732	mutation($mediaId: Int, $score: Float) {
 733		SaveMediaListEntry(mediaId: $mediaId, score: $score) {
 734			id
 735			mediaId
 736			score
 737		}
 738	}`
 739
 740	variables := map[string]interface{}{
 741		"mediaId": mediaID,
 742		"score":   score,
 743	}
 744
 745	headers := map[string]string{
 746		"Authorization": "Bearer " + token,
 747		"Content-Type":  "application/json",
 748	}
 749
 750	_, err = makePostRequest(url, query, variables, headers)
 751	if err != nil {
 752		return err
 753	}
 754
 755	CurdOut(fmt.Sprintf("Successfully rated anime (mediaId: %d) with score: %.2f", mediaID, score))
 756	return nil
 757}
 758
 759// Helper function to make POST requests
 760func makePostRequest(url, query string, variables map[string]interface{}, headers map[string]string) (map[string]interface{}, error) {
 761	requestBody, err := json.Marshal(map[string]interface{}{
 762		"query":     query,
 763		"variables": variables,
 764	})
 765	if err != nil {
 766		return nil, fmt.Errorf("failed to marshal request body: %w", err)
 767	}
 768
 769	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
 770	if err != nil {
 771		return nil, fmt.Errorf("failed to create request: %w", err)
 772	}
 773
 774	req.Header.Set("Content-Type", "application/json") // <-- Important!
 775	for key, value := range headers {
 776		req.Header.Set(key, value)
 777	}
 778
 779	client := &http.Client{}
 780	resp, err := client.Do(req)
 781	if err != nil {
 782		return nil, fmt.Errorf("failed to send request: %w", err)
 783	}
 784	defer resp.Body.Close()
 785
 786	body, err := io.ReadAll(resp.Body)
 787	if err != nil {
 788		return nil, fmt.Errorf("failed to read response body: %w", err)
 789	}
 790
 791	if resp.StatusCode != http.StatusOK {
 792		return nil, fmt.Errorf("failed with status %d: %s", resp.StatusCode, body)
 793	}
 794
 795	var responseData map[string]interface{}
 796	// Unmarshal the response into a map
 797	err = json.Unmarshal(body, &responseData)
 798	if err != nil {
 799		return nil, fmt.Errorf("failed to unmarshal response: %w", err)
 800	}
 801
 802	return responseData, nil
 803}
 804
 805func ParseAnimeList(input map[string]interface{}) AnimeList {
 806	var animeList AnimeList
 807	userCurdConfig := GetGlobalConfig()
 808
 809	toInt := func(value interface{}) int {
 810		switch v := value.(type) {
 811		case int:
 812			return v
 813		case float64:
 814			return int(v) // You could also use int(math.Round(v)) to round
 815		default:
 816			return 0 // Default value for unexpected types
 817		}
 818	}
 819
 820	safeString := func(value interface{}) string {
 821		if value == nil {
 822			return ""
 823		}
 824
 825		// Attempt to assert the value as a string
 826		if str, ok := value.(string); ok {
 827			return str
 828		}
 829
 830		// If it's not a string, return an empty string or handle it as needed
 831		return ""
 832	}
 833
 834	parseFuzzyDate := func(value interface{}) FuzzyDate {
 835		dateMap, ok := value.(map[string]interface{})
 836		if !ok || dateMap == nil {
 837			return FuzzyDate{}
 838		}
 839
 840		return FuzzyDate{
 841			Year:  toInt(dateMap["year"]),
 842			Month: toInt(dateMap["month"]),
 843			Day:   toInt(dateMap["day"]),
 844		}
 845	}
 846
 847	// Access the list entries in the input map
 848	if input["data"] == nil {
 849		Log("Anilist request failed")
 850		CurdOut("Anilist request failed")
 851		ExitCurd(fmt.Errorf("Anilist request failed"))
 852		return animeList
 853	}
 854	data := input["data"].(map[string]interface{})
 855	mediaList := data["MediaListCollection"].(map[string]interface{})["lists"].([]interface{})
 856
 857	for _, list := range mediaList {
 858		entries := list.(map[string]interface{})["entries"].([]interface{})
 859
 860		for _, entry := range entries {
 861			entryData := entry.(map[string]interface{})
 862			media := entryData["media"].(map[string]interface{})
 863			animeEntry := Entry{
 864				Media: Media{
 865					Duration: toInt(media["duration"]),
 866					Episodes: toInt(media["episodes"]),
 867					ID:       toInt(media["id"]),
 868					Title: AnimeTitle{
 869						English:  safeString(media["title"].(map[string]interface{})["english"]),
 870						Romaji:   safeString(media["title"].(map[string]interface{})["romaji"]),
 871						Japanese: safeString(media["title"].(map[string]interface{})["native"]),
 872					},
 873					Status: safeString(media["status"]),
 874				},
 875				Progress:    toInt(entryData["progress"]),
 876				Repeat:      toInt(entryData["repeat"]),
 877				Score:       entryData["score"].(float64),
 878				Status:      safeString(entryData["status"]), // Ensure status is fetched safely
 879				StartedAt:   parseFuzzyDate(entryData["startedAt"]),
 880				CompletedAt: parseFuzzyDate(entryData["completedAt"]),
 881			}
 882
 883			if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 884				animeEntry.CoverImage = safeString(media["coverImage"].(map[string]interface{})["large"])
 885			}
 886
 887			// Append entries based on their status
 888			switch animeEntry.Status {
 889			case "CURRENT":
 890				animeList.Watching = append(animeList.Watching, animeEntry)
 891			case "COMPLETED":
 892				animeList.Completed = append(animeList.Completed, animeEntry)
 893			case "PAUSED":
 894				animeList.Paused = append(animeList.Paused, animeEntry)
 895			case "DROPPED":
 896				animeList.Dropped = append(animeList.Dropped, animeEntry)
 897			case "PLANNING":
 898				animeList.Planning = append(animeList.Planning, animeEntry)
 899			case "REPEATING": // Anilist uses REPEATING for rewatching
 900				animeList.Rewatching = append(animeList.Rewatching, animeEntry)
 901			}
 902		}
 903	}
 904
 905	return animeList
 906}
 907
 908// FindAnimeByID searches for an anime by its ID in the AnimeList
 909func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
 910	id, err := strconv.Atoi(idStr)
 911	if err != nil {
 912		return nil, fmt.Errorf("invalid ID format: %s", idStr)
 913	}
 914
 915	// Define a slice of pointers to hold categories
 916	categories := [][]Entry{
 917		list.Watching,
 918		list.Completed,
 919		list.Paused,
 920		list.Dropped,
 921		list.Planning,
 922		list.Rewatching, // Add Rewatching list
 923	}
 924
 925	// Iterate through each category
 926	for _, category := range categories {
 927		for _, entry := range category {
 928			if entry.Media.ID == id {
 929				return &entry, nil // Return a pointer to the found entry
 930			}
 931		}
 932	}
 933
 934	return nil, fmt.Errorf("anime with ID %d not found", id) // Return an error if not found
 935}
 936
 937// FindAnimeByAnilistIDInAnimes searches for an anime by its AniList ID in a slice of Anime
 938func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error) {
 939	for i := range animes {
 940		if animes[i].AnilistId == anilistID {
 941			return &animes[i], nil
 942		}
 943	}
 944	return nil, fmt.Errorf("anime with ID %d not found", anilistID)
 945}
 946
 947// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token
 948func GetAnimeDataByID(id int, token string) (Anime, error) {
 949	url := "https://graphql.anilist.co"
 950	query := `
 951	query ($id: Int) {
 952		Media(id: $id, type: ANIME) {
 953			id
 954			episodes
 955			status
 956			nextAiringEpisode {
 957				episode
 958			}
 959		}
 960	}`
 961
 962	variables := map[string]interface{}{
 963		"id": id,
 964	}
 965
 966	headers := map[string]string{
 967		"Authorization": "Bearer " + token,
 968		"Content-Type":  "application/json",
 969	}
 970
 971	response, err := makePostRequest(url, query, variables, headers)
 972	if err != nil {
 973		return Anime{}, fmt.Errorf("failed to get anime data: %w", err)
 974	}
 975
 976	data, ok := response["data"].(map[string]interface{})
 977	if !ok {
 978		return Anime{}, fmt.Errorf("invalid response format: data field missing")
 979	}
 980
 981	media, ok := data["Media"].(map[string]interface{})
 982	if !ok {
 983		return Anime{}, fmt.Errorf("invalid response format: Media field missing")
 984	}
 985
 986	anime := Anime{
 987		AnilistId: id,
 988		IsAiring:  false,
 989	}
 990
 991	// Safely handle episodes field which might be nil for currently airing shows
 992	if episodes, ok := media["episodes"].(float64); ok {
 993		anime.TotalEpisodes = int(episodes)
 994	}
 995
 996	// Check status
 997	if status, ok := media["status"].(string); ok {
 998		anime.IsAiring = status == "RELEASING"
 999	}
1000
1001	// Double check with nextAiringEpisode
1002	if nextEp, ok := media["nextAiringEpisode"].(map[string]interface{}); ok && nextEp != nil {
1003		anime.IsAiring = true
1004	}
1005
1006	return anime, nil
1007}
1008
1009// SequelInfo holds information about a sequel anime
1010type SequelInfo struct {
1011	ID         int
1012	Title      AnimeTitle
1013	CoverImage string
1014	Episodes   int
1015	Status     string // "FINISHED", "RELEASING", "NOT_YET_RELEASED"
1016	SiteURL    string
1017}
1018
1019// GetAnimeSequel fetches sequel information for a given anime from AniList
1020// GetAnimeSequel fetches sequel information for a given anime from AniList
1021func GetAnimeSequel(animeID int, token string) ([]SequelInfo, error) {
1022	url := "https://graphql.anilist.co"
1023	query := `
1024	query ($id: Int) {
1025		Media(id: $id, type: ANIME) {
1026			relations {
1027				edges {
1028					relationType
1029					node {
1030						id
1031						title {
1032							romaji
1033							english
1034						}
1035						coverImage {
1036							large
1037						}
1038						episodes
1039						status
1040						siteUrl
1041					}
1042				}
1043			}
1044		}
1045	}`
1046
1047	variables := map[string]interface{}{
1048		"id": animeID,
1049	}
1050
1051	headers := map[string]string{
1052		"Authorization": "Bearer " + token,
1053		"Content-Type":  "application/json",
1054	}
1055
1056	response, err := makePostRequest(url, query, variables, headers)
1057	if err != nil {
1058		return nil, fmt.Errorf("failed to get anime relations: %w", err)
1059	}
1060
1061	data, ok := response["data"].(map[string]interface{})
1062	if !ok {
1063		return nil, fmt.Errorf("invalid response format: data field missing")
1064	}
1065
1066	media, ok := data["Media"].(map[string]interface{})
1067	if !ok {
1068		return nil, fmt.Errorf("invalid response format: Media field missing")
1069	}
1070
1071	relations, ok := media["relations"].(map[string]interface{})
1072	if !ok {
1073		return nil, nil // No relations found
1074	}
1075
1076	edges, ok := relations["edges"].([]interface{})
1077	if !ok || len(edges) == 0 {
1078		return nil, nil // No edges found
1079	}
1080
1081	var sequels []SequelInfo
1082
1083	// Look for a SEQUEL relation
1084	for _, edge := range edges {
1085		edgeData, ok := edge.(map[string]interface{})
1086		if !ok {
1087			continue
1088		}
1089
1090		relationType, ok := edgeData["relationType"].(string)
1091		if !ok || relationType != "SEQUEL" {
1092			continue
1093		}
1094
1095		node, ok := edgeData["node"].(map[string]interface{})
1096		if !ok {
1097			continue
1098		}
1099
1100		var sequel SequelInfo
1101
1102		// Parse ID
1103		if id, ok := node["id"].(float64); ok {
1104			sequel.ID = int(id)
1105		}
1106
1107		// Parse title
1108		if title, ok := node["title"].(map[string]interface{}); ok {
1109			if romaji, ok := title["romaji"].(string); ok {
1110				sequel.Title.Romaji = romaji
1111			}
1112			if english, ok := title["english"].(string); ok {
1113				sequel.Title.English = english
1114			}
1115		}
1116
1117		// Parse cover image
1118		if coverImage, ok := node["coverImage"].(map[string]interface{}); ok {
1119			if large, ok := coverImage["large"].(string); ok {
1120				sequel.CoverImage = large
1121			}
1122		}
1123
1124		// Parse episodes
1125		if episodes, ok := node["episodes"].(float64); ok {
1126			sequel.Episodes = int(episodes)
1127		}
1128
1129		// Parse status
1130		if status, ok := node["status"].(string); ok {
1131			sequel.Status = status
1132		}
1133
1134		// Parse siteUrl
1135		if siteUrl, ok := node["siteUrl"].(string); ok {
1136			sequel.SiteURL = siteUrl
1137		}
1138
1139		sequels = append(sequels, sequel)
1140	}
1141
1142	if len(sequels) == 0 {
1143		return nil, nil // No sequel found
1144	}
1145
1146	return sequels, nil
1147}
1148
1149// AddAnimeToList adds an anime to a specified list (CURRENT, PLANNING, PAUSED, DROPPED)
1150func AddAnimeToList(animeID int, status string, token string) error {
1151	url := "https://graphql.anilist.co"
1152	mutation := `
1153	mutation ($mediaId: Int, $status: MediaListStatus) {
1154		SaveMediaListEntry (mediaId: $mediaId, status: $status) {
1155			id
1156			status
1157		}
1158	}`
1159
1160	variables := map[string]interface{}{
1161		"mediaId": animeID,
1162		"status":  status,
1163	}
1164
1165	headers := map[string]string{
1166		"Authorization": "Bearer " + token,
1167		"Content-Type":  "application/json",
1168	}
1169
1170	_, err := makePostRequest(url, mutation, variables, headers)
1171	if err != nil {
1172		return fmt.Errorf("failed to add anime to list: %w", err)
1173	}
1174
1175	statusMap := map[string]string{
1176		"CURRENT":   "Currently Watching",
1177		"COMPLETED": "Completed",
1178		"PAUSED":    "On Hold",
1179		"DROPPED":   "Dropped",
1180		"PLANNING":  "Plan to Watch",
1181		"REPEATING": "Rewatching",
1182	}
1183
1184	CurdOut(fmt.Sprintf("Anime added to: %s", statusMap[status]))
1185	return nil
1186}
1187
1188// FindSequelInAnimeList searches for a sequel in the user's anime list and returns its status
1189func FindSequelInAnimeList(list AnimeList, sequelID int) (string, bool) {
1190	// Check all categories
1191	for _, entry := range list.Watching {
1192		if entry.Media.ID == sequelID {
1193			return "CURRENT", true
1194		}
1195	}
1196	for _, entry := range list.Planning {
1197		if entry.Media.ID == sequelID {
1198			return "PLANNING", true
1199		}
1200	}
1201	for _, entry := range list.Completed {
1202		if entry.Media.ID == sequelID {
1203			return "COMPLETED", true
1204		}
1205	}
1206	for _, entry := range list.Paused {
1207		if entry.Media.ID == sequelID {
1208			return "PAUSED", true
1209		}
1210	}
1211	for _, entry := range list.Dropped {
1212		if entry.Media.ID == sequelID {
1213			return "DROPPED", true
1214		}
1215	}
1216	for _, entry := range list.Rewatching {
1217		if entry.Media.ID == sequelID {
1218			return "REWATCHING", true
1219		}
1220	}
1221
1222	return "", false
1223}