internal/provider_mapping.go

1111 lines · 35136 bytes

35 symbols in this file
   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
 374	selected, err := selectWithOptionalMessage(config, options, "Provider search", message)
 375	if err != nil {
 376		return "", err
 377	}
 378	selected = NormalizeSelectionKey(selected)
 379	if SelectionMeansQuit(selected) {
 380		return "quit", nil
 381	}
 382	if SelectionMeansBack(selected) || selected.Key == "back" {
 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	selected, err := selectWithOptionalMessage(config, options, "Provider match", "We didn't find an automatic provider match.")
 402	if err != nil {
 403		return "", err
 404	}
 405	selected = NormalizeSelectionKey(selected)
 406	if SelectionMeansQuit(selected) {
 407		return "quit", nil
 408	}
 409	if SelectionMeansBack(selected) || selected.Key == "back" {
 410		return "back", nil
 411	}
 412	return selected.Key, nil
 413}
 414
 415// selectWithOptionalMessage uses Rofi -mesg when Rofi is on (no notify spam), else prints + ordered select.
 416func selectWithOptionalMessage(config *CurdConfig, options []SelectionOption, prompt, message string) (SelectionOption, error) {
 417	if config != nil && config.RofiSelection {
 418		return RofiSelectWithMessage(options, false, prompt, message)
 419	}
 420	if strings.TrimSpace(message) != "" {
 421		fmt.Println(message)
 422	}
 423	return promptSelectOrdered(options)
 424}
 425
 426func activeProviderName(config *CurdConfig, state *providerMappingSearchState) string {
 427	if state != nil && state.sequential {
 428		if name := state.currentProviderLabel(); name != "" {
 429			return name
 430		}
 431	}
 432	names := configuredProviderNames(config)
 433	if len(names) > 0 {
 434		return names[0]
 435	}
 436	return firstEnabledProviderName()
 437}
 438
 439func providerNameFromSelectionLabel(label string) string {
 440	label = strings.TrimSpace(label)
 441	if idx := strings.LastIndex(label, " ["); idx > 0 && strings.HasSuffix(label, "]") {
 442		name := strings.TrimSpace(label[idx+2 : len(label)-1])
 443		if normalized := normalizeProviderName(name); normalized != "" {
 444			return normalized
 445		}
 446	}
 447	return ""
 448}
 449
 450func providerNameFromSelection(config *CurdConfig, state *providerMappingSearchState, selected SelectionOption) string {
 451	if providerName, _, ok := ParseProviderQualifiedID(selected.Key); ok {
 452		return providerName
 453	}
 454	if name := providerNameFromSelectionLabel(selected.Label); name != "" {
 455		return name
 456	}
 457	return activeProviderName(config, state)
 458}
 459
 460func applyMatchedProviderMapping(config *CurdConfig, state *providerMappingSearchState, anime *Anime) {
 461	if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
 462		anime.ProviderName = providerName
 463		anime.ProviderId = rawProviderID
 464		return
 465	}
 466	anime.ProviderName = activeProviderName(config, state)
 467}
 468
 469func applySelectedProviderMapping(config *CurdConfig, state *providerMappingSearchState, anime *Anime, selected SelectionOption) {
 470	anime.ProviderId = selected.Key
 471	if providerName, rawProviderID, ok := ParseProviderQualifiedID(anime.ProviderId); ok {
 472		anime.ProviderName = providerName
 473		anime.ProviderId = rawProviderID
 474		return
 475	}
 476	anime.ProviderName = providerNameFromSelection(config, state, selected)
 477}
 478
 479func promptCustomProviderSearchQuery(config *CurdConfig, currentQuery, hint string) (string, bool, bool, error) {
 480	manualQuery, err := promptText(config, hint, true)
 481	if err != nil {
 482		return "", false, false, err
 483	}
 484	if manualQuery == "" {
 485		manualQuery = currentQuery
 486	}
 487	return manualQuery, false, false, nil
 488}
 489
 490func ResolveAnimeProviderMapping(config *CurdConfig, anime *Anime, query string, anilistEntry *Entry) (ProviderMappingOutcome, error) {
 491	return resolveAnimeProviderMapping(config, anime, query, anilistEntry, ManualProviderSearchEnabled(config))
 492}
 493
 494func resolveAnimeProviderMapping(config *CurdConfig, anime *Anime, query string, anilistEntry *Entry, manualOnly bool) (ProviderMappingOutcome, error) {
 495	state := &providerMappingSearchState{
 496		query:        query,
 497		allProviders: configuredProviderNames(config),
 498	}
 499
 500	for {
 501		Log(fmt.Sprintf("Searching for anime with query: %s, SubOrDub: %s, scope: %s", state.query, config.SubOrDub, state.currentProviderLabel()))
 502
 503		animeList, err := searchAnimeForMapping(config, state, config.SubOrDub)
 504		if err != nil {
 505			Log(fmt.Sprintf("Provider search failed: %v", err))
 506			action, actionErr := promptProviderSearchRecovery(config, state, fmt.Sprintf("Provider search failed for '%s': %v", state.query, err))
 507			if actionErr != nil {
 508				return ProviderMappingQuit, actionErr
 509			}
 510			outcome, cont, actionErr := handleProviderMappingAction(config, state, action, query)
 511			if actionErr != nil {
 512				return ProviderMappingQuit, actionErr
 513			}
 514			if !cont {
 515				return outcome, nil
 516			}
 517			continue
 518		}
 519
 520		if len(animeList) == 0 {
 521			action, actionErr := promptProviderSearchRecovery(config, state, "")
 522			if actionErr != nil {
 523				return ProviderMappingQuit, actionErr
 524			}
 525			outcome, cont, actionErr := handleProviderMappingAction(config, state, action, query)
 526			if actionErr != nil {
 527				return ProviderMappingQuit, actionErr
 528			}
 529			if !cont {
 530				return outcome, nil
 531			}
 532			continue
 533		}
 534
 535		anime.ProviderId = ""
 536		if !manualOnly && autoMatchProviderListing(config, anime, animeList, state.query, anilistEntry) {
 537			applyMatchedProviderMapping(config, state, anime)
 538			return ProviderMappingOK, nil
 539		}
 540
 541		if manualOnly {
 542			for {
 543				hint := ManualProviderSearchHint(config, anilistEntry, state.query, config.SubOrDub)
 544				selected, selectErr := promptProviderSearchSelectionWithHint(config, animeList, anilistEntry, hint)
 545				if selectErr != nil {
 546					Log(fmt.Sprintf("Failed to select anime: %v", selectErr))
 547				} else {
 548					switch selected.Key {
 549					case "-1":
 550						// fall through to recovery menu
 551					case "-2":
 552						return ProviderMappingBack, nil
 553					default:
 554						applySelectedProviderMapping(config, state, anime, selected)
 555						return ProviderMappingOK, nil
 556					}
 557				}
 558
 559				action, actionErr := promptProviderMatchRecovery(config, state)
 560				if actionErr != nil {
 561					return ProviderMappingQuit, actionErr
 562				}
 563				switch action {
 564				case "pick":
 565					continue
 566				case "custom", "next_provider":
 567					outcome, cont, handleErr := handleProviderMappingAction(config, state, action, query)
 568					if handleErr != nil {
 569						return ProviderMappingQuit, handleErr
 570					}
 571					if !cont {
 572						return outcome, nil
 573					}
 574					break
 575				case "back":
 576					return ProviderMappingBack, nil
 577				case "quit":
 578					return ProviderMappingQuit, nil
 579				default:
 580					continue
 581				}
 582				break
 583			}
 584			continue
 585		}
 586
 587		for {
 588			action, actionErr := promptProviderMatchRecovery(config, state)
 589			if actionErr != nil {
 590				return ProviderMappingQuit, actionErr
 591			}
 592
 593			switch action {
 594			case "pick":
 595				CurdOut("Select the correct anime from the search results.")
 596				selected, selectErr := promptProviderSearchSelection(config, animeList, anilistEntry)
 597				if selectErr != nil {
 598					Log(fmt.Sprintf("Failed to select anime: %v", selectErr))
 599					continue
 600				}
 601				switch selected.Key {
 602				case "-1":
 603					continue
 604				case "-2":
 605					return ProviderMappingBack, nil
 606				default:
 607					applySelectedProviderMapping(config, state, anime, selected)
 608					return ProviderMappingOK, nil
 609				}
 610			case "custom", "next_provider":
 611				outcome, cont, handleErr := handleProviderMappingAction(config, state, action, query)
 612				if handleErr != nil {
 613					return ProviderMappingQuit, handleErr
 614				}
 615				if !cont {
 616					return outcome, nil
 617				}
 618				break
 619			case "back":
 620				return ProviderMappingBack, nil
 621			case "quit":
 622				return ProviderMappingQuit, nil
 623			default:
 624				continue
 625			}
 626			break
 627		}
 628	}
 629}
 630
 631func RemapProviderAnime(userCurdConfig *CurdConfig, user *User, databaseAnimes *[]Anime) {
 632	if userCurdConfig == nil || user == nil {
 633		return
 634	}
 635
 636	if err := RefreshUserAnimeList(userCurdConfig, user); err != nil {
 637		Log(fmt.Sprintf("Failed to refresh anime list before provider remap: %v", err))
 638	}
 639
 640	if user.ListSync != nil {
 641		user.AnimeList = user.ListSync.Current()
 642	}
 643
 644	options := buildCategorySelectionOptions(user.AnimeList, "ALL")
 645	if len(options) == 0 {
 646		CurdOut("No anime found in your lists.")
 647		return
 648	}
 649
 650	var selected SelectionOption
 651	var err error
 652	if userCurdConfig.RofiSelection && userCurdConfig.ImagePreview {
 653		preview := buildCategoryPreviewOptions(user.AnimeList, "ALL")
 654		selected, err = DynamicSelectPreview(preview, false)
 655	} else {
 656		selected, err = DynamicSelect(options)
 657	}
 658	if err != nil {
 659		Log(fmt.Sprintf("Failed to select anime for provider remap: %v", err))
 660		return
 661	}
 662	if selected.Key == "-1" || selected.Key == "-2" {
 663		return
 664	}
 665
 666	anilistEntry, err := FindAnimeByAnilistID(user.AnimeList, selected.Key)
 667	if err != nil {
 668		Log(fmt.Sprintf("Failed to resolve selected anime: %v", err))
 669		CurdOut("Could not find the selected anime in your lists.")
 670		return
 671	}
 672
 673	historyPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "curd_history.txt")
 674	if databaseAnimes != nil {
 675		if existing := LocalFindAnime(*databaseAnimes, anilistEntry.Media.ID, ""); existing != nil {
 676			CurdOut(fmt.Sprintf("Current provider mapping: %s (%s)", CurrentAnimeProviderName(existing), existing.ProviderId))
 677		} else {
 678			CurdOut("No saved provider mapping in local history yet.")
 679		}
 680	}
 681
 682	query := mediaDisplayTitle(anilistEntry.Media, userCurdConfig)
 683	anime := Anime{
 684		AnilistId:     anilistEntry.Media.ID,
 685		MalId:         anilistEntry.Media.MalID,
 686		Title:         anilistEntry.Media.Title,
 687		TotalEpisodes: anilistEntry.Media.Episodes,
 688		CoverImage:    anilistEntry.CoverImage,
 689	}
 690
 691	outcome, mappingErr := resolveAnimeProviderMapping(userCurdConfig, &anime, query, anilistEntry, true)
 692	if mappingErr != nil {
 693		Log(fmt.Sprintf("Provider remap failed: %v", mappingErr))
 694		CurdOut("Failed to update provider mapping.")
 695		return
 696	}
 697	switch outcome {
 698	case ProviderMappingBack, ProviderMappingQuit:
 699		return
 700	case ProviderMappingOK:
 701		if err := persistRemappedProvider(historyPath, databaseAnimes, anilistEntry, &anime, query); err != nil {
 702			Log(fmt.Sprintf("Failed to save remapped provider: %v", err))
 703			CurdOut("Provider selected, but failed to save mapping to local history.")
 704			return
 705		}
 706		CurdOut(fmt.Sprintf("Updated provider mapping to %s (%s).", anime.ProviderName, anime.ProviderId))
 707	}
 708}
 709
 710func persistRemappedProvider(historyPath string, databaseAnimes *[]Anime, anilistEntry *Entry, anime *Anime, animeName string) error {
 711	if anime == nil || anilistEntry == nil {
 712		return fmt.Errorf("missing anime data")
 713	}
 714
 715	episode := 1
 716	playbackTime := 0
 717	duration := 0
 718	if databaseAnimes != nil {
 719		if existing := LocalFindAnime(*databaseAnimes, anime.AnilistId, ""); existing != nil {
 720			episode = existing.Ep.Number
 721			playbackTime = existing.Ep.Player.PlaybackTime
 722			duration = existing.Ep.Duration
 723			if savedName := GetAnimeName(*existing); savedName != "" {
 724				animeName = savedName
 725			}
 726		}
 727	}
 728	if episode <= 0 {
 729		episode = nextEpisodeFromProgress(anilistEntry.Progress)
 730		if episode <= 0 {
 731			episode = 1
 732		}
 733	}
 734
 735	if err := LocalRemapAnimeProvider(historyPath, anime.AnilistId, anime.ProviderName, anime.ProviderId, animeName, episode, playbackTime, duration); err != nil {
 736		return err
 737	}
 738	if databaseAnimes != nil {
 739		*databaseAnimes = LocalGetAllAnime(historyPath)
 740	}
 741	return nil
 742}
 743
 744func handleProviderMappingAction(config *CurdConfig, state *providerMappingSearchState, action, defaultQuery string) (ProviderMappingOutcome, bool, error) {
 745	switch action {
 746	case "custom":
 747		hint := fmt.Sprintf("Enter a search name for configured providers (current: '%s').", state.query)
 748		newQuery, _, _, err := promptCustomProviderSearchQuery(config, state.query, hint)
 749		if err != nil {
 750			return ProviderMappingQuit, false, err
 751		}
 752		state.query = newQuery
 753		state.resetToAllProviders()
 754		return ProviderMappingOK, true, nil
 755	case "next_provider":
 756		if !state.advanceToNextProvider() {
 757			CurdOut("No more providers left to try.")
 758			action, err := promptProviderSearchRecovery(config, state, "No more providers left to try.")
 759			if err != nil {
 760				return ProviderMappingQuit, false, err
 761			}
 762			return handleProviderMappingAction(config, state, action, defaultQuery)
 763		}
 764		return ProviderMappingOK, true, nil
 765	case "back":
 766		return ProviderMappingBack, false, nil
 767	case "quit":
 768		return ProviderMappingQuit, false, nil
 769	default:
 770		return ProviderMappingOK, true, nil
 771	}
 772}
 773
 774func untrackedProviderSearchSelection(config *CurdConfig, query string, animeList []SelectionOption) (SelectionOption, error) {
 775	if ManualProviderSearchEnabled(config) {
 776		hint := ManualProviderSearchHint(config, nil, query, config.SubOrDub)
 777		return promptProviderSearchSelectionWithHint(config, animeList, nil, hint)
 778	}
 779	return promptProviderSearchSelection(config, animeList, nil)
 780}
 781
 782func RemapAnimeProviderOnEpisodeFailure(config *CurdConfig, anime *Anime, anilistEntry *Entry) bool {
 783	query := GetAnimeName(*anime)
 784	if query == "" {
 785		query = anime.Title.Romaji
 786	}
 787	if query == "" {
 788		query = anime.Title.English
 789	}
 790	if query == "" {
 791		return false
 792	}
 793
 794	CurdOut("Wrong match is common — search again and pick the right title.")
 795	anime.ProviderId = ""
 796	anime.ProviderName = ""
 797	anime.Ep.NextEpisode = NextEpisode{}
 798
 799	outcome, err := ResolveAnimeProviderMapping(config, anime, query, anilistEntry)
 800	if err != nil {
 801		Log(fmt.Sprintf("Provider remap failed: %v", err))
 802		return false
 803	}
 804	return outcome == ProviderMappingOK
 805}
 806
 807// episodeLinkFailureRecoveryOptions builds ranked recovery actions for a dead-end
 808// after preferred (and optional alternate) resolve already failed.
 809// Labels are numbered so DynamicSelect's alphabetical sort preserves priority.
 810func episodeLinkFailureRecoveryOptions(preferredMode string, includeAudio bool) []SelectionOption {
 811	preferredMode = normalizeTranslationType(preferredMode)
 812	alternateMode := alternateTranslationType(preferredMode)
 813
 814	// No numeric indices — callers must use DynamicSelectPreserveOrder / Rofi (keeps order).
 815	options := []SelectionOption{
 816		{Key: "remap", Label: "Search for this anime again"},
 817	}
 818	if includeAudio {
 819		options = append(options, SelectionOption{
 820			Key:   "audio",
 821			Label: fmt.Sprintf("Try other audio (%s)", alternateMode),
 822		})
 823	}
 824	options = append(options, SelectionOption{
 825		Key:   "episode",
 826		Label: "Change episode number (if this one is wrong)",
 827	})
 828	return options
 829}
 830
 831func episodeLinkFailureDiagnosis(config *CurdConfig, anime *Anime, lastErr error) string {
 832	title := "this anime"
 833	if anime != nil {
 834		if name := strings.TrimSpace(GetAnimeName(*anime)); name != "" {
 835			title = name
 836		}
 837	}
 838
 839	epNo := 0
 840	if anime != nil {
 841		epNo = anime.Ep.Number
 842	}
 843
 844	mode := "sub"
 845	if config != nil {
 846		mode = normalizeTranslationType(config.SubOrDub)
 847	}
 848
 849	providers := configuredProviderNames(config)
 850	tried := "none"
 851	if len(providers) > 0 {
 852		tried = strings.Join(providers, ", ")
 853	}
 854
 855	var b strings.Builder
 856	fmt.Fprintf(&b, "Couldn't find Episode %d (%s) for %q\nTried: %s", epNo, mode, title, tried)
 857	if lastErr != nil {
 858		reason := strings.TrimSpace(lastErr.Error())
 859		if reason != "" {
 860			// Keep diagnosis readable — one short reason line.
 861			if len(reason) > 160 {
 862				reason = reason[:157] + "..."
 863			}
 864			fmt.Fprintf(&b, "\nReason: %s", reason)
 865		}
 866	}
 867	return b.String()
 868}
 869
 870// promptEpisodeLinkFailureRecovery shows a diagnosed dead-end after full resolve
 871// failure. Returns: remap | audio | episode | back
 872// DynamicSelect still injects Back/Quit; both map to "back" (single exit path).
 873func promptEpisodeLinkFailureRecovery(config *CurdConfig, anime *Anime, lastErr error, includeAudio bool) string {
 874	preferredMode := "sub"
 875	if config != nil {
 876		preferredMode = normalizeTranslationType(config.SubOrDub)
 877	}
 878
 879	diagnosis := episodeLinkFailureDiagnosis(config, anime, lastErr)
 880	options := episodeLinkFailureRecoveryOptions(preferredMode, includeAudio)
 881
 882	var selected SelectionOption
 883	var err error
 884	if config != nil && config.RofiSelection {
 885		// Put diagnosis in Rofi -mesg — avoid one notify-send per CurdOut line.
 886		selected, err = RofiSelectWithMessage(options, false, "Playback recovery", diagnosis)
 887	} else {
 888		fmt.Println(diagnosis)
 889		selected, err = promptSelectOrdered(options)
 890	}
 891	if err != nil {
 892		return "back"
 893	}
 894	selected = NormalizeSelectionKey(selected)
 895	if SelectionMeansQuit(selected) {
 896		return "quit"
 897	}
 898	if SelectionMeansBack(selected) || selected.Key == "" {
 899		return "back"
 900	}
 901	switch selected.Key {
 902	case "remap", "audio", "episode":
 903		return selected.Key
 904	default:
 905		return "back"
 906	}
 907}
 908
 909// resolveEpisodeLinksWithRecovery runs preferred-first playback resolve and only
 910// after that fails presents the diagnosed recovery menu. Returns ok=false when
 911// the user backs out.
 912func resolveEpisodeLinksWithRecovery(config *CurdConfig, anime *Anime, anilistEntry *Entry, allowAnimepaheReselect bool) (ProviderEpisodeResult, bool) {
 913	if config == nil || anime == nil {
 914		return ProviderEpisodeResult{}, false
 915	}
 916
 917	var lastErr error
 918	includeAudio := true
 919	attemptedAnimepaheReselect := false
 920
 921	for {
 922		result, err := ResolveEpisodeURLForPlayback(*config, anime, anime.Ep.Number)
 923		if err == nil && len(result.Links) > 0 {
 924			return result, true
 925		}
 926		if err != nil {
 927			lastErr = err
 928		} else {
 929			lastErr = fmt.Errorf("no episode links found")
 930		}
 931		Log(fmt.Sprintf("ResolveEpisodeURLForPlayback failed for ep %d: %v", anime.Ep.Number, lastErr))
 932
 933		// One-shot Animepahe stale-mapping reselect (tracked path helper).
 934		if allowAnimepaheReselect && !attemptedAnimepaheReselect {
 935			attemptedAnimepaheReselect = true
 936			if reselectProviderAnime(config, anime, lastErr) {
 937				result, err = ResolveEpisodeURLForPlayback(*config, anime, anime.Ep.Number)
 938				if err == nil && len(result.Links) > 0 {
 939					Log(fmt.Sprintf("Successfully retrieved %s/%s episode link after provider reselect", result.ProviderName, result.Mode))
 940					return result, true
 941				}
 942				if err != nil {
 943					lastErr = err
 944				} else {
 945					lastErr = fmt.Errorf("no episode links found after provider reselect")
 946				}
 947				Log(fmt.Sprintf("ResolveEpisodeURL still failed after provider reselect: %v", lastErr))
 948			}
 949		}
 950
 951		switch promptEpisodeLinkFailureRecovery(config, anime, lastErr, includeAudio) {
 952		case "remap":
 953			if RemapAnimeProviderOnEpisodeFailure(config, anime, anilistEntry) {
 954				// Full preferred-first resolve again after remap.
 955				continue
 956			}
 957			lastErr = fmt.Errorf("provider remap did not produce a new mapping")
 958		case "audio":
 959			// Explicit re-offer of alternate mode (user may have declined earlier).
 960			altResult, altErr := ResolveEpisodeURLAlternateModeWithPrompt(*config, anime, anime.Ep.Number, nil)
 961			if altErr == nil && len(altResult.Links) > 0 {
 962				return altResult, true
 963			}
 964			if altErr != nil {
 965				lastErr = altErr
 966				if strings.Contains(strings.ToLower(altErr.Error()), "no ") &&
 967					strings.Contains(strings.ToLower(altErr.Error()), "streams available") {
 968					includeAudio = false
 969				}
 970			} else {
 971				lastErr = fmt.Errorf("no %s streams available", alternateTranslationType(config.SubOrDub))
 972				includeAudio = false
 973			}
 974			CurdOut("Still no playable stream after trying other audio.")
 975		case "episode":
 976			episodePrompt := "Change episode number (if this one is wrong)"
 977			providerName, providerID := AnimeProviderID(anime)
 978			if providerID != "" {
 979				if episodeList, listErr := EpisodesList(QualifyProviderID(providerName, providerID), config.SubOrDub); listErr == nil && len(episodeList) > 0 {
 980					episodePrompt = fmt.Sprintf("Change episode number (provider lists up to %v)", episodeList[len(episodeList)-1])
 981				}
 982			}
 983			episodeNumber, promptErr := promptPositiveEpisodeNumber(config, episodePrompt)
 984			if promptErr != nil {
 985				Log("Invalid episode input: " + promptErr.Error())
 986				CurdOut("Invalid episode number")
 987				continue
 988			}
 989			anime.Ep.Number = episodeNumber
 990			anime.Ep.NextEpisode = NextEpisode{}
 991			// Re-run full preferred-first resolve for the new episode.
 992			continue
 993		default:
 994			return ProviderEpisodeResult{}, false
 995		}
 996	}
 997}
 998
 999func ResolveUntrackedProviderSearch(config *CurdConfig, initialQuery string) (providerID, providerName string, back bool, err error) {
1000	state := &providerMappingSearchState{
1001		query:        initialQuery,
1002		allProviders: configuredProviderNames(config),
1003	}
1004
1005	for {
1006		animeList, searchErr := searchAnimeForMapping(config, state, config.SubOrDub)
1007		if searchErr != nil {
1008			Log(fmt.Sprintf("Provider search failed: %v", searchErr))
1009			action, actionErr := promptProviderSearchRecovery(config, state, fmt.Sprintf("Provider search failed for '%s': %v", state.query, searchErr))
1010			if actionErr != nil {
1011				return "", "", false, actionErr
1012			}
1013			if action == "back" {
1014				return "", "", true, nil
1015			}
1016			if action == "quit" {
1017				return "", "", false, nil
1018			}
1019			_, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
1020			if handleErr != nil {
1021				return "", "", false, handleErr
1022			}
1023			if !cont {
1024				return "", "", false, nil
1025			}
1026			continue
1027		}
1028
1029		if len(animeList) == 0 {
1030			action, actionErr := promptProviderSearchRecovery(config, state, "")
1031			if actionErr != nil {
1032				return "", "", false, actionErr
1033			}
1034			if action == "back" {
1035				return "", "", true, nil
1036			}
1037			if action == "quit" {
1038				return "", "", false, nil
1039			}
1040			_, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
1041			if handleErr != nil {
1042				return "", "", false, handleErr
1043			}
1044			if !cont {
1045				return "", "", false, nil
1046			}
1047			continue
1048		}
1049
1050		selected, selectErr := untrackedProviderSearchSelection(config, state.query, animeList)
1051		if selectErr != nil {
1052			Log(fmt.Sprintf("Failed to select anime: %v", selectErr))
1053			action, actionErr := promptProviderMatchRecovery(config, state)
1054			if actionErr != nil {
1055				return "", "", false, actionErr
1056			}
1057			if action == "back" {
1058				return "", "", true, nil
1059			}
1060			if action == "quit" {
1061				return "", "", false, nil
1062			}
1063			_, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
1064			if handleErr != nil {
1065				return "", "", false, handleErr
1066			}
1067			if !cont {
1068				return "", "", false, nil
1069			}
1070			continue
1071		}
1072
1073		switch selected.Key {
1074		case "-1":
1075			action, actionErr := promptProviderMatchRecovery(config, state)
1076			if actionErr != nil {
1077				return "", "", false, actionErr
1078			}
1079			if action == "back" {
1080				return "", "", true, nil
1081			}
1082			if action == "quit" {
1083				return "", "", false, nil
1084			}
1085			_, cont, handleErr := handleProviderMappingAction(config, state, action, initialQuery)
1086			if handleErr != nil {
1087				return "", "", false, handleErr
1088			}
1089			if !cont {
1090				return "", "", false, nil
1091			}
1092			continue
1093		case "-2":
1094			return "", "", true, nil
1095		default:
1096			if name, rawID, ok := ParseProviderQualifiedID(selected.Key); ok {
1097				return rawID, name, false, nil
1098			}
1099			return selected.Key, providerNameFromSelection(config, state, selected), false, nil
1100		}
1101	}
1102}
1103
1104func malIDFromProviderExtraData(extra any) int {
1105	switch item := extra.(type) {
1106	case anipub.SearchItem:
1107		return item.MalID
1108	default:
1109		return 0
1110	}
1111}