internal/provider_mapping.go

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