internal/anilist.go

1222 lines · 29892 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
 808	toInt := func(value interface{}) int {
 809		switch v := value.(type) {
 810		case int:
 811			return v
 812		case float64:
 813			return int(v) // You could also use int(math.Round(v)) to round
 814		default:
 815			return 0 // Default value for unexpected types
 816		}
 817	}
 818
 819	safeString := func(value interface{}) string {
 820		if value == nil {
 821			return ""
 822		}
 823
 824		// Attempt to assert the value as a string
 825		if str, ok := value.(string); ok {
 826			return str
 827		}
 828
 829		// If it's not a string, return an empty string or handle it as needed
 830		return ""
 831	}
 832
 833	parseFuzzyDate := func(value interface{}) FuzzyDate {
 834		dateMap, ok := value.(map[string]interface{})
 835		if !ok || dateMap == nil {
 836			return FuzzyDate{}
 837		}
 838
 839		return FuzzyDate{
 840			Year:  toInt(dateMap["year"]),
 841			Month: toInt(dateMap["month"]),
 842			Day:   toInt(dateMap["day"]),
 843		}
 844	}
 845
 846	// Access the list entries in the input map
 847	if input["data"] == nil {
 848		Log("Anilist request failed")
 849		CurdOut("Anilist request failed")
 850		ExitCurd(fmt.Errorf("Anilist request failed"))
 851		return animeList
 852	}
 853	data := input["data"].(map[string]interface{})
 854	mediaList := data["MediaListCollection"].(map[string]interface{})["lists"].([]interface{})
 855
 856	for _, list := range mediaList {
 857		entries := list.(map[string]interface{})["entries"].([]interface{})
 858
 859		for _, entry := range entries {
 860			entryData := entry.(map[string]interface{})
 861			media := entryData["media"].(map[string]interface{})
 862			animeEntry := Entry{
 863				Media: Media{
 864					Duration: toInt(media["duration"]),
 865					Episodes: toInt(media["episodes"]),
 866					ID:       toInt(media["id"]),
 867					Title: AnimeTitle{
 868						English:  safeString(media["title"].(map[string]interface{})["english"]),
 869						Romaji:   safeString(media["title"].(map[string]interface{})["romaji"]),
 870						Japanese: safeString(media["title"].(map[string]interface{})["native"]),
 871					},
 872					Status: safeString(media["status"]),
 873				},
 874				Progress:    toInt(entryData["progress"]),
 875				Repeat:      toInt(entryData["repeat"]),
 876				Score:       entryData["score"].(float64),
 877				Status:      safeString(entryData["status"]), // Ensure status is fetched safely
 878				StartedAt:   parseFuzzyDate(entryData["startedAt"]),
 879				CompletedAt: parseFuzzyDate(entryData["completedAt"]),
 880			}
 881
 882			if coverImage, ok := media["coverImage"].(map[string]interface{}); ok {
 883				animeEntry.CoverImage = safeString(coverImage["large"])
 884			}
 885
 886			// Append entries based on their status
 887			switch animeEntry.Status {
 888			case "CURRENT":
 889				animeList.Watching = append(animeList.Watching, animeEntry)
 890			case "COMPLETED":
 891				animeList.Completed = append(animeList.Completed, animeEntry)
 892			case "PAUSED":
 893				animeList.Paused = append(animeList.Paused, animeEntry)
 894			case "DROPPED":
 895				animeList.Dropped = append(animeList.Dropped, animeEntry)
 896			case "PLANNING":
 897				animeList.Planning = append(animeList.Planning, animeEntry)
 898			case "REPEATING": // Anilist uses REPEATING for rewatching
 899				animeList.Rewatching = append(animeList.Rewatching, animeEntry)
 900			}
 901		}
 902	}
 903
 904	return animeList
 905}
 906
 907// FindAnimeByID searches for an anime by its ID in the AnimeList
 908func FindAnimeByAnilistID(list AnimeList, idStr string) (*Entry, error) {
 909	id, err := strconv.Atoi(idStr)
 910	if err != nil {
 911		return nil, fmt.Errorf("invalid ID format: %s", idStr)
 912	}
 913
 914	// Define a slice of pointers to hold categories
 915	categories := [][]Entry{
 916		list.Watching,
 917		list.Completed,
 918		list.Paused,
 919		list.Dropped,
 920		list.Planning,
 921		list.Rewatching, // Add Rewatching list
 922	}
 923
 924	// Iterate through each category
 925	for _, category := range categories {
 926		for _, entry := range category {
 927			if entry.Media.ID == id {
 928				return &entry, nil // Return a pointer to the found entry
 929			}
 930		}
 931	}
 932
 933	return nil, fmt.Errorf("anime with ID %d not found", id) // Return an error if not found
 934}
 935
 936// FindAnimeByAnilistIDInAnimes searches for an anime by its AniList ID in a slice of Anime
 937func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error) {
 938	for i := range animes {
 939		if animes[i].AnilistId == anilistID {
 940			return &animes[i], nil
 941		}
 942	}
 943	return nil, fmt.Errorf("anime with ID %d not found", anilistID)
 944}
 945
 946// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token
 947func GetAnimeDataByID(id int, token string) (Anime, error) {
 948	url := "https://graphql.anilist.co"
 949	query := `
 950	query ($id: Int) {
 951		Media(id: $id, type: ANIME) {
 952			id
 953			episodes
 954			status
 955			nextAiringEpisode {
 956				episode
 957			}
 958		}
 959	}`
 960
 961	variables := map[string]interface{}{
 962		"id": id,
 963	}
 964
 965	headers := map[string]string{
 966		"Authorization": "Bearer " + token,
 967		"Content-Type":  "application/json",
 968	}
 969
 970	response, err := makePostRequest(url, query, variables, headers)
 971	if err != nil {
 972		return Anime{}, fmt.Errorf("failed to get anime data: %w", err)
 973	}
 974
 975	data, ok := response["data"].(map[string]interface{})
 976	if !ok {
 977		return Anime{}, fmt.Errorf("invalid response format: data field missing")
 978	}
 979
 980	media, ok := data["Media"].(map[string]interface{})
 981	if !ok {
 982		return Anime{}, fmt.Errorf("invalid response format: Media field missing")
 983	}
 984
 985	anime := Anime{
 986		AnilistId: id,
 987		IsAiring:  false,
 988	}
 989
 990	// Safely handle episodes field which might be nil for currently airing shows
 991	if episodes, ok := media["episodes"].(float64); ok {
 992		anime.TotalEpisodes = int(episodes)
 993	}
 994
 995	// Check status
 996	if status, ok := media["status"].(string); ok {
 997		anime.IsAiring = status == "RELEASING"
 998	}
 999
1000	// Double check with nextAiringEpisode
1001	if nextEp, ok := media["nextAiringEpisode"].(map[string]interface{}); ok && nextEp != nil {
1002		anime.IsAiring = true
1003	}
1004
1005	return anime, nil
1006}
1007
1008// SequelInfo holds information about a sequel anime
1009type SequelInfo struct {
1010	ID         int
1011	Title      AnimeTitle
1012	CoverImage string
1013	Episodes   int
1014	Status     string // "FINISHED", "RELEASING", "NOT_YET_RELEASED"
1015	SiteURL    string
1016}
1017
1018// GetAnimeSequel fetches sequel information for a given anime from AniList
1019// GetAnimeSequel fetches sequel information for a given anime from AniList
1020func GetAnimeSequel(animeID int, token string) ([]SequelInfo, error) {
1021	url := "https://graphql.anilist.co"
1022	query := `
1023	query ($id: Int) {
1024		Media(id: $id, type: ANIME) {
1025			relations {
1026				edges {
1027					relationType
1028					node {
1029						id
1030						title {
1031							romaji
1032							english
1033						}
1034						coverImage {
1035							large
1036						}
1037						episodes
1038						status
1039						siteUrl
1040					}
1041				}
1042			}
1043		}
1044	}`
1045
1046	variables := map[string]interface{}{
1047		"id": animeID,
1048	}
1049
1050	headers := map[string]string{
1051		"Authorization": "Bearer " + token,
1052		"Content-Type":  "application/json",
1053	}
1054
1055	response, err := makePostRequest(url, query, variables, headers)
1056	if err != nil {
1057		return nil, fmt.Errorf("failed to get anime relations: %w", err)
1058	}
1059
1060	data, ok := response["data"].(map[string]interface{})
1061	if !ok {
1062		return nil, fmt.Errorf("invalid response format: data field missing")
1063	}
1064
1065	media, ok := data["Media"].(map[string]interface{})
1066	if !ok {
1067		return nil, fmt.Errorf("invalid response format: Media field missing")
1068	}
1069
1070	relations, ok := media["relations"].(map[string]interface{})
1071	if !ok {
1072		return nil, nil // No relations found
1073	}
1074
1075	edges, ok := relations["edges"].([]interface{})
1076	if !ok || len(edges) == 0 {
1077		return nil, nil // No edges found
1078	}
1079
1080	var sequels []SequelInfo
1081
1082	// Look for a SEQUEL relation
1083	for _, edge := range edges {
1084		edgeData, ok := edge.(map[string]interface{})
1085		if !ok {
1086			continue
1087		}
1088
1089		relationType, ok := edgeData["relationType"].(string)
1090		if !ok || relationType != "SEQUEL" {
1091			continue
1092		}
1093
1094		node, ok := edgeData["node"].(map[string]interface{})
1095		if !ok {
1096			continue
1097		}
1098
1099		var sequel SequelInfo
1100
1101		// Parse ID
1102		if id, ok := node["id"].(float64); ok {
1103			sequel.ID = int(id)
1104		}
1105
1106		// Parse title
1107		if title, ok := node["title"].(map[string]interface{}); ok {
1108			if romaji, ok := title["romaji"].(string); ok {
1109				sequel.Title.Romaji = romaji
1110			}
1111			if english, ok := title["english"].(string); ok {
1112				sequel.Title.English = english
1113			}
1114		}
1115
1116		// Parse cover image
1117		if coverImage, ok := node["coverImage"].(map[string]interface{}); ok {
1118			if large, ok := coverImage["large"].(string); ok {
1119				sequel.CoverImage = large
1120			}
1121		}
1122
1123		// Parse episodes
1124		if episodes, ok := node["episodes"].(float64); ok {
1125			sequel.Episodes = int(episodes)
1126		}
1127
1128		// Parse status
1129		if status, ok := node["status"].(string); ok {
1130			sequel.Status = status
1131		}
1132
1133		// Parse siteUrl
1134		if siteUrl, ok := node["siteUrl"].(string); ok {
1135			sequel.SiteURL = siteUrl
1136		}
1137
1138		sequels = append(sequels, sequel)
1139	}
1140
1141	if len(sequels) == 0 {
1142		return nil, nil // No sequel found
1143	}
1144
1145	return sequels, nil
1146}
1147
1148// AddAnimeToList adds an anime to a specified list (CURRENT, PLANNING, PAUSED, DROPPED)
1149func AddAnimeToList(animeID int, status string, token string) error {
1150	url := "https://graphql.anilist.co"
1151	mutation := `
1152	mutation ($mediaId: Int, $status: MediaListStatus) {
1153		SaveMediaListEntry (mediaId: $mediaId, status: $status) {
1154			id
1155			status
1156		}
1157	}`
1158
1159	variables := map[string]interface{}{
1160		"mediaId": animeID,
1161		"status":  status,
1162	}
1163
1164	headers := map[string]string{
1165		"Authorization": "Bearer " + token,
1166		"Content-Type":  "application/json",
1167	}
1168
1169	_, err := makePostRequest(url, mutation, variables, headers)
1170	if err != nil {
1171		return fmt.Errorf("failed to add anime to list: %w", err)
1172	}
1173
1174	statusMap := map[string]string{
1175		"CURRENT":   "Currently Watching",
1176		"COMPLETED": "Completed",
1177		"PAUSED":    "On Hold",
1178		"DROPPED":   "Dropped",
1179		"PLANNING":  "Plan to Watch",
1180		"REPEATING": "Rewatching",
1181	}
1182
1183	CurdOut(fmt.Sprintf("Anime added to: %s", statusMap[status]))
1184	return nil
1185}
1186
1187// FindSequelInAnimeList searches for a sequel in the user's anime list and returns its status
1188func FindSequelInAnimeList(list AnimeList, sequelID int) (string, bool) {
1189	// Check all categories
1190	for _, entry := range list.Watching {
1191		if entry.Media.ID == sequelID {
1192			return "CURRENT", true
1193		}
1194	}
1195	for _, entry := range list.Planning {
1196		if entry.Media.ID == sequelID {
1197			return "PLANNING", true
1198		}
1199	}
1200	for _, entry := range list.Completed {
1201		if entry.Media.ID == sequelID {
1202			return "COMPLETED", true
1203		}
1204	}
1205	for _, entry := range list.Paused {
1206		if entry.Media.ID == sequelID {
1207			return "PAUSED", true
1208		}
1209	}
1210	for _, entry := range list.Dropped {
1211		if entry.Media.ID == sequelID {
1212			return "DROPPED", true
1213		}
1214	}
1215	for _, entry := range list.Rewatching {
1216		if entry.Media.ID == sequelID {
1217			return "REWATCHING", true
1218		}
1219	}
1220
1221	return "", false
1222}