internal/provider_mapping.go

923 lines · 28308 bytes

  1package internal
  2
  3import (
  4	"fmt"
  5	"io"
  6	"net/http"
  7	"os"
  8	"path/filepath"
  9	"regexp"
 10	"strconv"
 11	"strings"
 12
 13	"github.com/wraient/curd/internal/providers/animepahe"
 14	"github.com/wraient/curd/internal/providers/anipub"
 15)
 16
 17type ProviderMappingOutcome int
 18
 19const (
 20	ProviderMappingOK ProviderMappingOutcome = iota
 21	ProviderMappingBack
 22	ProviderMappingQuit
 23)
 24
 25type providerMappingSearchState struct {
 26	query         string
 27	allProviders  []string
 28	sequential    bool
 29	providerIndex int
 30}
 31
 32func (s *providerMappingSearchState) activeProviders() []string {
 33	if !s.sequential {
 34		return s.allProviders
 35	}
 36	if s.providerIndex >= len(s.allProviders) {
 37		return nil
 38	}
 39	return []string{s.allProviders[s.providerIndex]}
 40}
 41
 42func (s *providerMappingSearchState) currentProviderLabel() string {
 43	if !s.sequential {
 44		return "all configured providers"
 45	}
 46	if s.providerIndex >= len(s.allProviders) {
 47		return ""
 48	}
 49	return s.allProviders[s.providerIndex]
 50}
 51
 52func (s *providerMappingSearchState) nextProviderLabel() string {
 53	if len(s.allProviders) == 0 {
 54		return ""
 55	}
 56	if !s.sequential {
 57		if len(s.allProviders) <= 1 {
 58			return ""
 59		}
 60		return s.allProviders[0]
 61	}
 62	next := s.providerIndex + 1
 63	if next < len(s.allProviders) {
 64		return s.allProviders[next]
 65	}
 66	return ""
 67}
 68
 69func (s *providerMappingSearchState) advanceToNextProvider() bool {
 70	if len(s.allProviders) == 0 {
 71		return false
 72	}
 73	if !s.sequential {
 74		if len(s.allProviders) <= 1 {
 75			return false
 76		}
 77		s.sequential = true
 78		s.providerIndex = 0
 79		return true
 80	}
 81	s.providerIndex++
 82	return s.providerIndex < len(s.allProviders)
 83}
 84
 85func (s *providerMappingSearchState) resetToAllProviders() {
 86	s.sequential = false
 87	s.providerIndex = 0
 88}
 89
 90func searchAnimeForMapping(config *CurdConfig, state *providerMappingSearchState, mode string) ([]SelectionOption, error) {
 91	providers := state.activeProviders()
 92	if len(providers) == 0 {
 93		return nil, nil
 94	}
 95	if !state.sequential && len(providers) == len(state.allProviders) {
 96		return SearchAnime(state.query, mode)
 97	}
 98	return searchAnimeWithProviders(providers, state.query, mode)
 99}
100
101func confirmProviderMatch(option SelectionOption, reason string) bool {
102	label := option.Label
103	if label == "" {
104		label = option.Title
105	}
106	if label == "" {
107		label = option.Key
108	}
109
110	CurdOut(fmt.Sprintf("Provider match found by %s: %s", reason, label))
111	selected, err := promptSelect([]SelectionOption{
112		{Key: "use", Label: "Use this match"},
113		{Key: "manual", Label: "Select manually"},
114	})
115	if err != nil {
116		Log(fmt.Sprintf("Error confirming provider match: %v", err))
117		return false
118	}
119	return selected.Key == "use"
120}
121
122func autoMatchProviderListing(config *CurdConfig, anime *Anime, animeList []SelectionOption, userQuery string, anilistEntry *Entry) bool {
123	anilistIDStr := strconv.Itoa(anime.AnilistId)
124	var jikanUrls []string
125	fetchedJikan := false
126
127	anilistRegex := regexp.MustCompile(`anilistcdn/media/anime/cover/(?:large|medium)/(?:bx)?(\d+)`)
128	malRegex := regexp.MustCompile(`myanimelist\.net/images/anime/[^/]+/([^/]+\.jpg)`)
129	senshiPosterRE := regexp.MustCompile(`/posters/(\d+)(?:\.webp)?`)
130
131	if anime.MalId == 0 {
132		anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
133	}
134	if anime.MalId != 0 {
135		malIDStr := strconv.Itoa(anime.MalId)
136		for i, option := range animeList {
137			if option.Key == malIDStr {
138				Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s', Thumbnail='%s'", i, option.Key, option.Label, option.Thumbnail))
139				anime.ProviderId = option.Key
140				Log(fmt.Sprintf("Found MAL ID provider key match! Setting ProviderId to: %s", anime.ProviderId))
141				return true
142			}
143		}
144	}
145
146	for i, option := range animeList {
147		Log(fmt.Sprintf("Checking option %d: Key='%s', Label='%s', Thumbnail='%s'", i, option.Key, option.Label, option.Thumbnail))
148
149		if malID := malIDFromProviderExtraData(option.ExtraData); malID != 0 && anime.MalId != 0 && malID == anime.MalId {
150			anime.ProviderId = option.Key
151			Log(fmt.Sprintf("Found provider MAL ID extra-data match! Setting ProviderId to: %s", anime.ProviderId))
152			return true
153		}
154
155		if strings.Contains(option.Thumbnail, "anilist.co") {
156			matches := anilistRegex.FindStringSubmatch(option.Thumbnail)
157			if len(matches) > 1 && matches[1] == anilistIDStr {
158				anime.ProviderId = option.Key
159				Log(fmt.Sprintf("Found Anilist Thumbnail match! Setting ProviderId to: %s", anime.ProviderId))
160				return true
161			}
162		} else if strings.Contains(option.Thumbnail, "myanimelist.net") {
163			matches := malRegex.FindStringSubmatch(option.Thumbnail)
164			if len(matches) > 1 {
165				fileName := matches[1]
166
167				if !fetchedJikan {
168					if anime.MalId == 0 {
169						anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
170					}
171					if anime.MalId != 0 {
172						urls, err := FetchJikanPictures(anime.MalId)
173						if err != nil {
174							Log(fmt.Sprintf("Failed to fetch Jikan pictures: %v", err))
175						} else {
176							jikanUrls = urls
177						}
178					}
179					fetchedJikan = true
180				}
181
182				for _, url := range jikanUrls {
183					if strings.HasSuffix(url, "/"+fileName) || strings.Contains(url, fileName) {
184						anime.ProviderId = option.Key
185						Log(fmt.Sprintf("Found MyAnimeList Thumbnail match (%s)! Setting ProviderId to: %s", fileName, anime.ProviderId))
186						return true
187					}
188				}
189			}
190		} else if strings.Contains(option.Thumbnail, "/posters/") {
191			matches := senshiPosterRE.FindStringSubmatch(option.Thumbnail)
192			if len(matches) > 1 && anime.MalId != 0 && matches[1] == strconv.Itoa(anime.MalId) {
193				anime.ProviderId = option.Key
194				Log(fmt.Sprintf("Found Senshi MAL poster match! Setting ProviderId to: %s", anime.ProviderId))
195				return true
196			}
197		}
198	}
199
200	if bestMatch, ok := confidentProviderSearchMatch(animeList, anime, userQuery); ok {
201		anime.ProviderId = bestMatch.Key
202		Log(fmt.Sprintf("Found confident provider title match! Setting ProviderId to: %s (%s)", anime.ProviderId, bestMatch.Label))
203		return true
204	}
205
206	if ProviderEnabled("animepahe") && ProviderStackContains(config, "animepahe") {
207		Log("Attempting deep metadata matching and exact AniList meta tag check for Animepahe...")
208
209		targetAnilistID := strconv.Itoa(anime.AnilistId)
210		var bestMatch *SelectionOption
211		var highestScore int
212
213		if anime.MalId == 0 {
214			anime.MalId, _ = GetAnimeMalID(anime.AnilistId)
215		}
216
217		var malData *JikanAnimeData
218		if anime.MalId != 0 {
219			malData, _ = FetchJikanAnimeData(anime.MalId)
220		}
221
222		for i := range animeList {
223			opt := &animeList[i]
224			optionProviderName, rawProviderID, ok := ParseProviderQualifiedID(opt.Key)
225			if ok {
226				if optionProviderName != "animepahe" {
227					continue
228				}
229			} else {
230				rawProviderID = opt.Key
231				if configuredProviderNames(config)[0] != "animepahe" {
232					continue
233				}
234			}
235			score := 0
236
237			if malData != nil && opt.ExtraData != nil {
238				if paheData, ok := opt.ExtraData.(animepahe.SearchItem); ok {
239					paheTitleLower := strings.ToLower(paheData.Title)
240					malTitleLower := strings.ToLower(malData.Title)
241					malTitleEngLower := strings.ToLower(malData.TitleEnglish)
242					malTitleJapLower := strings.ToLower(malData.TitleJapanese)
243
244					if paheTitleLower == malTitleLower || (malTitleEngLower != "" && paheTitleLower == malTitleEngLower) || (malTitleJapLower != "" && paheTitleLower == malTitleJapLower) {
245						score += 5
246					} else if strings.Contains(paheTitleLower, malTitleLower) || strings.Contains(malTitleLower, paheTitleLower) ||
247						(malTitleEngLower != "" && (strings.Contains(paheTitleLower, malTitleEngLower) || strings.Contains(malTitleEngLower, paheTitleLower))) {
248						score += 2
249					}
250
251					if paheData.Year > 0 && malData.Year > 0 && paheData.Year == malData.Year {
252						score += 3
253					}
254					if paheData.Season != "" && malData.Season != "" && strings.EqualFold(paheData.Season, malData.Season) {
255						score += 2
256					}
257					if paheData.Type != "" && malData.Type != "" && strings.EqualFold(paheData.Type, malData.Type) {
258						score += 2
259					}
260					if paheData.Episodes > 0 && malData.Episodes > 0 && paheData.Episodes == malData.Episodes {
261						score += 2
262					} else if (paheData.Episodes == 0 && malData.Status == "Currently Airing") || (malData.Episodes == 0 && paheData.Status == "Currently Airing") {
263						score += 2
264					}
265					if strings.EqualFold(paheData.Status, malData.Status) {
266						score += 1
267					}
268				}
269			} else if strings.Contains(strings.ToLower(opt.Title), strings.ToLower(string(userQuery))) {
270				score += 2
271			}
272
273			if score >= 2 || len(animeList) <= 3 {
274				animeRef := animepahe.ParseProviderID(rawProviderID)
275				if animeRef.Session == "" {
276					continue
277				}
278				animeUrl := fmt.Sprintf("https://animepahe.pw/anime/%s", animeRef.Session)
279				Log(fmt.Sprintf("Fetching %s to check exact AniList meta tag...", animeUrl))
280				req, err := animepahe.NewPageRequest(animeUrl)
281				if err != nil {
282					Log(fmt.Sprintf("Failed to build animepahe detail request %s: %v", animeUrl, err))
283					continue
284				}
285
286				resp, err := sharedHTTPClient.Do(req)
287				if err != nil {
288					Log(fmt.Sprintf("Failed to fetch animepahe detail page %s: %v", animeUrl, err))
289					continue
290				}
291				body, readErr := io.ReadAll(resp.Body)
292				resp.Body.Close()
293				if readErr != nil {
294					Log(fmt.Sprintf("Failed to read animepahe detail page %s: %v", animeUrl, readErr))
295					continue
296				}
297				if resp.StatusCode == http.StatusOK {
298					bodyStr := string(body)
299
300					metaTag := fmt.Sprintf(`<meta name="anilist" content="%s">`, targetAnilistID)
301					if strings.Contains(bodyStr, metaTag) {
302						Log(fmt.Sprintf("FOUND EXACT ANILIST META TAG MATCH in %s!", opt.Title))
303						bestMatch = opt
304						highestScore = 100
305						break
306					}
307
308					malMetaTag := fmt.Sprintf(`<meta name="mal" content="%d">`, anime.MalId)
309					if anime.MalId != 0 && strings.Contains(bodyStr, malMetaTag) {
310						Log(fmt.Sprintf("FOUND EXACT MAL META TAG MATCH in %s!", opt.Title))
311						bestMatch = opt
312						highestScore = 100
313						break
314					}
315				}
316			}
317
318			if score > highestScore {
319				highestScore = score
320				bestMatch = opt
321			}
322		}
323
324		if bestMatch != nil && highestScore == 100 {
325			anime.ProviderId = bestMatch.Key
326			Log(fmt.Sprintf("Found EXACT meta tag match! Score: %d. Setting ProviderId to: %s", highestScore, anime.ProviderId))
327			return true
328		}
329		if bestMatch != nil {
330			Log(fmt.Sprintf("Highest match score was %d (needed 100 for Animepahe exact meta tag match). Not selecting automatically to prevent false positives.", highestScore))
331			if confirmProviderMatch(*bestMatch, "Animepahe metadata") {
332				anime.ProviderId = bestMatch.Key
333				Log(fmt.Sprintf("User confirmed Animepahe match. Setting ProviderId to: %s", anime.ProviderId))
334				return true
335			}
336		}
337	}
338
339	if anilistEntry != nil {
340		targetLabel := fmt.Sprintf("%v (%d episodes)", userQuery, anilistEntry.Media.Episodes)
341		for _, option := range animeList {
342			if fmt.Sprintf("%s (%d episodes)", option.Title, anilistEntry.Media.Episodes) == targetLabel {
343				if confirmProviderMatch(option, "title and episode count") {
344					anime.ProviderId = option.Key
345					Log(fmt.Sprintf("User confirmed exact text match. Setting ProviderId to: %s", anime.ProviderId))
346					return true
347				}
348				break
349			}
350		}
351		Log(fmt.Sprintf("No exact match found for label '%s'. Will require manual selection.", targetLabel))
352	}
353
354	return anime.ProviderId != ""
355}
356
357func promptProviderSearchRecovery(config *CurdConfig, state *providerMappingSearchState, reason string) (action string, err error) {
358	options := []SelectionOption{
359		{Key: "custom", Label: "Search with a different name"},
360	}
361	if next := state.nextProviderLabel(); next != "" {
362		options = append(options, SelectionOption{
363			Key:   "next_provider",
364			Label: fmt.Sprintf("Try next provider (%s)", next),
365		})
366	}
367	options = append(options, SelectionOption{Key: "back", Label: "Back to menu"})
368
369	message := reason
370	if message == "" {
371		message = fmt.Sprintf("No results found for '%s' on %s.", state.query, state.currentProviderLabel())
372	}
373	CurdOut(message)
374
375	selected, err := promptSelect(options)
376	if err != nil {
377		return "", err
378	}
379	if selected.Key == "-1" {
380		return "quit", nil
381	}
382	if selected.Key == "-2" {
383		return "back", nil
384	}
385	return selected.Key, nil
386}
387
388func promptProviderMatchRecovery(config *CurdConfig, state *providerMappingSearchState) (action string, err error) {
389	options := []SelectionOption{
390		{Key: "pick", Label: "Pick from search results"},
391		{Key: "custom", Label: "Search with a different name"},
392	}
393	if next := state.nextProviderLabel(); next != "" {
394		options = append(options, SelectionOption{
395			Key:   "next_provider",
396			Label: fmt.Sprintf("Try next provider (%s)", next),
397		})
398	}
399	options = append(options, SelectionOption{Key: "back", Label: "Back to menu"})
400
401	CurdOut("We didn't find an automatic provider match.")
402	selected, err := promptSelect(options)
403	if err != nil {
404		return "", err
405	}
406	if selected.Key == "-1" {
407		return "quit", nil
408	}
409	if selected.Key == "-2" {
410		return "back", nil
411	}
412	return selected.Key, nil
413}
414
415func activeProviderName(config *CurdConfig, state *providerMappingSearchState) string {
416	if state != nil && state.sequential {
417		if name := state.currentProviderLabel(); name != "" {
418			return name
419		}
420	}
421	names := configuredProviderNames(config)
422	if len(names) > 0 {
423		return names[0]
424	}
425	return firstEnabledProviderName()
426}
427
428func providerNameFromSelectionLabel(label string) string {
429	label = strings.TrimSpace(label)
430	if idx := strings.LastIndex(label, " ["); idx > 0 && strings.HasSuffix(label, "]") {
431		name := strings.TrimSpace(label[idx+2 : len(label)-1])
432		if normalized := normalizeProviderName(name); normalized != "" {
433			return normalized
434		}
435	}
436	return ""
437}
438
439func providerNameFromSelection(config *CurdConfig, state *providerMappingSearchState, selected SelectionOption) string {
440	if providerName, _, ok := ParseProviderQualifiedID(selected.Key); ok {
441		return providerName
442	}
443	if name := providerNameFromSelectionLabel(selected.Label); name != "" {
444		return name
445	}
446	return activeProviderName(config, state)
447}
448
449func applyMatchedProviderMapping(config *CurdConfig, state *providerMappingSearchState, anime *Anime) {
450	if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
451		anime.ProviderName = providerName
452		anime.ProviderId = rawProviderID
453		return
454	}
455	anime.ProviderName = activeProviderName(config, state)
456}
457
458func applySelectedProviderMapping(config *CurdConfig, state *providerMappingSearchState, anime *Anime, selected SelectionOption) {
459	anime.ProviderId = selected.Key
460	if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
461		anime.ProviderName = providerName
462		anime.ProviderId = rawProviderID
463		return
464	}
465	anime.ProviderName = providerNameFromSelection(config, state, selected)
466}
467
468func promptCustomProviderSearchQuery(config *CurdConfig, currentQuery, hint string) (string, bool, bool, error) {
469	manualQuery, err := promptText(config, hint, true)
470	if err != nil {
471		return "", false, false, err
472	}
473	if manualQuery == "" {
474		manualQuery = currentQuery
475	}
476	return manualQuery, false, false, nil
477}
478
479func ResolveAnimeProviderMapping(config *CurdConfig, anime *Anime, query string, anilistEntry *Entry) (ProviderMappingOutcome, error) {
480	return resolveAnimeProviderMapping(config, anime, query, anilistEntry, ManualProviderSearchEnabled(config))
481}
482
483func resolveAnimeProviderMapping(config *CurdConfig, anime *Anime, query string, anilistEntry *Entry, manualOnly bool) (ProviderMappingOutcome, error) {
484	state := &providerMappingSearchState{
485		query:        query,
486		allProviders: configuredProviderNames(config),
487	}
488
489	for {
490		Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s, scope: %s", state.query, config.SubOrDub, state.currentProviderLabel()))
491
492		animeList, err := searchAnimeForMapping(config, state, config.SubOrDub)
493		if err != nil {
494			Log(fmt.Sprintf("Provider search failed: %v", err))
495			action, actionErr := promptProviderSearchRecovery(config, state, fmt.Sprintf("Provider search failed for '%s': %v", state.query, err))
496			if actionErr != nil {
497				return ProviderMappingQuit, actionErr
498			}
499			outcome, cont, actionErr := handleProviderMappingAction(config, state, action, query)
500			if actionErr != nil {
501				return ProviderMappingQuit, actionErr
502			}
503			if !cont {
504				return outcome, nil
505			}
506			continue
507		}
508
509		if len(animeList) == 0 {
510			action, actionErr := promptProviderSearchRecovery(config, state, "")
511			if actionErr != nil {
512				return ProviderMappingQuit, actionErr
513			}
514			outcome, cont, actionErr := handleProviderMappingAction(config, state, action, query)
515			if actionErr != nil {
516				return ProviderMappingQuit, actionErr
517			}
518			if !cont {
519				return outcome, nil
520			}
521			continue
522		}
523
524		anime.ProviderId = ""
525		if !manualOnly && autoMatchProviderListing(config, anime, animeList, state.query, anilistEntry) {
526			applyMatchedProviderMapping(config, state, anime)
527			return ProviderMappingOK, nil
528		}
529
530		if manualOnly {
531			for {
532				hint := ManualProviderSearchHint(config, anilistEntry, state.query, config.SubOrDub)
533				selected, selectErr := promptProviderSearchSelectionWithHint(config, animeList, anilistEntry, hint)
534				if selectErr != nil {
535					Log(fmt.Sprintf("Failed to select anime: %v", selectErr))
536				} else {
537					switch selected.Key {
538					case "-1":
539						// fall through to recovery menu
540					case "-2":
541						return ProviderMappingBack, nil
542					default:
543						applySelectedProviderMapping(config, state, anime, selected)
544						return ProviderMappingOK, nil
545					}
546				}
547
548				action, actionErr := promptProviderMatchRecovery(config, state)
549				if actionErr != nil {
550					return ProviderMappingQuit, actionErr
551				}
552				switch action {
553				case "pick":
554					continue
555				case "custom", "next_provider":
556					outcome, cont, handleErr := handleProviderMappingAction(config, state, action, query)
557					if handleErr != nil {
558						return ProviderMappingQuit, handleErr
559					}
560					if !cont {
561						return outcome, nil
562					}
563					break
564				case "back":
565					return ProviderMappingBack, nil
566				case "quit":
567					return ProviderMappingQuit, nil
568				default:
569					continue
570				}
571				break
572			}
573			continue
574		}
575
576		for {
577			action, actionErr := promptProviderMatchRecovery(config, state)
578			if actionErr != nil {
579				return ProviderMappingQuit, actionErr
580			}
581
582			switch action {
583			case "pick":
584				CurdOut("Select the correct anime from the search results.")
585				selected, selectErr := promptProviderSearchSelection(config, animeList, anilistEntry)
586				if selectErr != nil {
587					Log(fmt.Sprintf("Failed to select anime: %v", selectErr))
588					continue
589				}
590				switch selected.Key {
591				case "-1":
592					continue
593				case "-2":
594					return ProviderMappingBack, nil
595				default:
596					applySelectedProviderMapping(config, state, anime, selected)
597					return ProviderMappingOK, nil
598				}
599			case "custom", "next_provider":
600				outcome, cont, handleErr := handleProviderMappingAction(config, state, action, query)
601				if handleErr != nil {
602					return ProviderMappingQuit, handleErr
603				}
604				if !cont {
605					return outcome, nil
606				}
607				break
608			case "back":
609				return ProviderMappingBack, nil
610			case "quit":
611				return ProviderMappingQuit, nil
612			default:
613				continue
614			}
615			break
616		}
617	}
618}
619
620func RemapProviderAnime(userCurdConfig *CurdConfig, user *User, databaseAnimes *[]Anime) {
621	if userCurdConfig == nil || user == nil {
622		return
623	}
624
625	if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
626		Log(fmt.Sprintf("Failed to refresh anime list before provider remap: %v", err))
627	}
628
629	if user.ListSync != nil {
630		user.AnimeList = user.ListSync.Current()
631	}
632
633	options := buildCategorySelectionOptions(user.AnimeList, "ALL")
634	if len(options) == 0 {
635		CurdOut("No anime found in your lists.")
636		return
637	}
638
639	var selected SelectionOption
640	var err error
641	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
642		preview := buildCategoryPreviewOptions(user.AnimeList, "ALL")
643		selected, err = DynamicSelectPreview(preview, false)
644	} else {
645		selected, err = DynamicSelect(options)
646	}
647	if err != nil {
648		Log(fmt.Sprintf("Failed to select anime for provider remap: %v", err))
649		return
650	}
651	if selected.Key == "-1" || selected.Key == "-2" {
652		return
653	}
654
655	anilistEntry, err := FindAnimeByAnilistID(user.AnimeList, selected.Key)
656	if err != nil {
657		Log(fmt.Sprintf("Failed to resolve selected anime: %v", err))
658		CurdOut("Could not find the selected anime in your lists.")
659		return
660	}
661
662	historyPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_history.txt")
663	if databaseAnimes != nil {
664		if existing := LocalFindAnime(*databaseAnimes, anilistEntry.Media.ID, ""); existing != nil {
665			CurdOut(fmt.Sprintf("Current provider mapping: %s (%s)", CurrentAnimeProviderName(existing), existing.ProviderId))
666		} else {
667			CurdOut("No saved provider mapping in local history yet.")
668		}
669	}
670
671	query := mediaDisplayTitle(anilistEntry.Media, userCurdConfig)
672	anime := Anime{
673		AnilistId:     anilistEntry.Media.ID,
674		MalId:         anilistEntry.Media.MalID,
675		Title:         anilistEntry.Media.Title,
676		TotalEpisodes: anilistEntry.Media.Episodes,
677		CoverImage:    anilistEntry.CoverImage,
678	}
679
680	outcome, mappingErr := resolveAnimeProviderMapping(userCurdConfig, &anime, query, anilistEntry, true)
681	if mappingErr != nil {
682		Log(fmt.Sprintf("Provider remap failed: %v", mappingErr))
683		CurdOut("Failed to update provider mapping.")
684		return
685	}
686	switch outcome {
687	case ProviderMappingBack, ProviderMappingQuit:
688		return
689	case ProviderMappingOK:
690		if err := persistRemappedProvider(historyPath, databaseAnimes, anilistEntry, &anime, query); err != nil {
691			Log(fmt.Sprintf("Failed to save remapped provider: %v", err))
692			CurdOut("Provider selected, but failed to save mapping to local history.")
693			return
694		}
695		CurdOut(fmt.Sprintf("Updated provider mapping to %s (%s).", anime.ProviderName, anime.ProviderId))
696	}
697}
698
699func persistRemappedProvider(historyPath string, databaseAnimes *[]Anime, anilistEntry *Entry, anime *Anime, animeName string) error {
700	if anime == nil || anilistEntry == nil {
701		return fmt.Errorf("missing anime data")
702	}
703
704	episode := 1
705	playbackTime := 0
706	duration := 0
707	if databaseAnimes != nil {
708		if existing := LocalFindAnime(*databaseAnimes, anime.AnilistId, ""); existing != nil {
709			episode = existing.Ep.Number
710			playbackTime = existing.Ep.Player.PlaybackTime
711			duration = existing.Ep.Duration
712			if savedName := GetAnimeName(*existing); savedName != "" {
713				animeName = savedName
714			}
715		}
716	}
717	if episode <= 0 {
718		episode = nextEpisodeFromProgress(anilistEntry.Progress)
719		if episode <= 0 {
720			episode = 1
721		}
722	}
723
724	if err := LocalRemapAnimeProvider(historyPath, anime.AnilistId, anime.ProviderName, anime.ProviderId, animeName, episode, playbackTime, duration); err != nil {
725		return err
726	}
727	if databaseAnimes != nil {
728		*databaseAnimes = LocalGetAllAnime(historyPath)
729	}
730	return nil
731}
732
733func handleProviderMappingAction(config *CurdConfig, state *providerMappingSearchState, action, defaultQuery string) (ProviderMappingOutcome, bool, error) {
734	switch action {
735	case "custom":
736		hint := fmt.Sprintf("Enter a search name for configured providers (current: '%s').", state.query)
737		newQuery, _, _, err := promptCustomProviderSearchQuery(config, state.query, hint)
738		if err != nil {
739			return ProviderMappingQuit, false, err
740		}
741		state.query = newQuery
742		state.resetToAllProviders()
743		return ProviderMappingOK, true, nil
744	case "next_provider":
745		if !state.advanceToNextProvider() {
746			CurdOut("No more providers left to try.")
747			action, err := promptProviderSearchRecovery(config, state, "No more providers left to try.")
748			if err != nil {
749				return ProviderMappingQuit, false, err
750			}
751			return handleProviderMappingAction(config, state, action, defaultQuery)
752		}
753		return ProviderMappingOK, true, nil
754	case "back":
755		return ProviderMappingBack, false, nil
756	case "quit":
757		return ProviderMappingQuit, false, nil
758	default:
759		return ProviderMappingOK, true, nil
760	}
761}
762
763func untrackedProviderSearchSelection(config *CurdConfig, query string, animeList []SelectionOption) (SelectionOption, error) {
764	if ManualProviderSearchEnabled(config) {
765		hint := ManualProviderSearchHint(config, nil, query, config.SubOrDub)
766		return promptProviderSearchSelectionWithHint(config, animeList, nil, hint)
767	}
768	return promptProviderSearchSelection(config, animeList, nil)
769}
770
771func RemapAnimeProviderOnEpisodeFailure(config *CurdConfig, anime *Anime, anilistEntry *Entry) bool {
772	query := GetAnimeName(*anime)
773	if query == "" {
774		query = anime.Title.Romaji
775	}
776	if query == "" {
777		query = anime.Title.English
778	}
779	if query == "" {
780		return false
781	}
782
783	CurdOut("Could not get an episode link with the current provider mapping.")
784	anime.ProviderId = ""
785	anime.ProviderName = ""
786	anime.Ep.NextEpisode = NextEpisode{}
787
788	outcome, err := ResolveAnimeProviderMapping(config, anime, query, anilistEntry)
789	if err != nil {
790		Log(fmt.Sprintf("Provider remap failed: %v", err))
791		return false
792	}
793	return outcome == ProviderMappingOK
794}
795
796func promptEpisodeLinkFailureRecovery(config *CurdConfig) string {
797	selected, err := promptSelect([]SelectionOption{
798		{Key: "remap", Label: "Search providers again"},
799		{Key: "episode", Label: "Try a different episode number"},
800		{Key: "quit", Label: "Cancel playback"},
801	})
802	if err != nil {
803		return "quit"
804	}
805	if selected.Key == "-1" || selected.Key == "-2" {
806		return "quit"
807	}
808	return selected.Key
809}
810
811func ResolveUntrackedProviderSearch(config *CurdConfig, initialQuery string) (providerID, providerName string, back bool, err error) {
812	state := &providerMappingSearchState{
813		query:        initialQuery,
814		allProviders: configuredProviderNames(config),
815	}
816
817	for {
818		animeList, searchErr := searchAnimeForMapping(config, state, config.SubOrDub)
819		if searchErr != nil {
820			Log(fmt.Sprintf("Provider search failed: %v", searchErr))
821			action, actionErr := promptProviderSearchRecovery(config, state, fmt.Sprintf("Provider search failed for '%s': %v", state.query, searchErr))
822			if actionErr != nil {
823				return "", "", false, actionErr
824			}
825			if action == "back" {
826				return "", "", true, nil
827			}
828			if action == "quit" {
829				return "", "", false, nil
830			}
831			_, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
832			if handleErr != nil {
833				return "", "", false, handleErr
834			}
835			if !cont {
836				return "", "", false, nil
837			}
838			continue
839		}
840
841		if len(animeList) == 0 {
842			action, actionErr := promptProviderSearchRecovery(config, state, "")
843			if actionErr != nil {
844				return "", "", false, actionErr
845			}
846			if action == "back" {
847				return "", "", true, nil
848			}
849			if action == "quit" {
850				return "", "", false, nil
851			}
852			_, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
853			if handleErr != nil {
854				return "", "", false, handleErr
855			}
856			if !cont {
857				return "", "", false, nil
858			}
859			continue
860		}
861
862		selected, selectErr := untrackedProviderSearchSelection(config, state.query, animeList)
863		if selectErr != nil {
864			Log(fmt.Sprintf("Failed to select anime: %v", selectErr))
865			action, actionErr := promptProviderMatchRecovery(config, state)
866			if actionErr != nil {
867				return "", "", false, actionErr
868			}
869			if action == "back" {
870				return "", "", true, nil
871			}
872			if action == "quit" {
873				return "", "", false, nil
874			}
875			_, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
876			if handleErr != nil {
877				return "", "", false, handleErr
878			}
879			if !cont {
880				return "", "", false, nil
881			}
882			continue
883		}
884
885		switch selected.Key {
886		case "-1":
887			action, actionErr := promptProviderMatchRecovery(config, state)
888			if actionErr != nil {
889				return "", "", false, actionErr
890			}
891			if action == "back" {
892				return "", "", true, nil
893			}
894			if action == "quit" {
895				return "", "", false, nil
896			}
897			_, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
898			if handleErr != nil {
899				return "", "", false, handleErr
900			}
901			if !cont {
902				return "", "", false, nil
903			}
904			continue
905		case "-2":
906			return "", "", true, nil
907		default:
908			if name, rawID, ok := ParseProviderQualifiedID(selected.Key); ok {
909				return rawID, name, false, nil
910			}
911			return selected.Key, providerNameFromSelection(config, state, selected), false, nil
912		}
913	}
914}
915
916func malIDFromProviderExtraData(extra any) int {
917	switch item := extra.(type) {
918	case anipub.SearchItem:
919		return item.MalID
920	default:
921		return 0
922	}
923}