import type { Source, MediaProfile } from '@shared/ipc'
import { resolveProfile, type ProfileDefaults } from '@shared/profileResolve'
import type { DownloadItem } from './downloadTypes'

/** The per-download group a retry re-resolves from current config. */
export type RetryOptionGroup = Pick<
  DownloadItem,
  'options' | 'extraArgs' | 'collectionOutputTemplate'
>

/**
 * Re-resolve a failed download's post-processing option group from the CURRENT
 * source profile / global settings, using the same precedence enqueue does
 * (resolveProfile). This is what lets a retry pick up a settings change made
 * after the item was queued — e.g. turning SponsorBlock-remove off — instead of
 * replaying the options frozen at add time.
 *
 * Only downloads tied to a Library source are re-resolved: their options always
 * derived from the source/global config in the first place. `mediaItemId` is
 * `<sourceId>:<videoId>`, so the source id is its prefix. Returned as a partial so
 * the caller can spread it over the item.
 *
 *  - no mediaItemId (a manual paste)  → null: it carried the user's explicit
 *    per-download choices, so retry must not overwrite them.
 *  - source since deleted             → null: nothing to resolve against; keep
 *    whatever options the item already had.
 *  - otherwise                        → the profile's group, or the globals when
 *    the source points at no (or a dangling) profile.
 *
 * Distinct from the history re-download path, which deliberately KEEPS an item's
 * frozen options to reproduce an identical file (L87); a retry's goal is instead
 * to get a failed download to succeed under the user's current configuration.
 */
export function pickRetryOptions(
  mediaItemId: string | undefined,
  sources: Source[],
  profiles: MediaProfile[],
  defaults: ProfileDefaults
): RetryOptionGroup | null {
  const sourceId = mediaItemId?.split(':')[0]
  if (!sourceId) return null
  const src = sources.find((s) => s.id === sourceId)
  if (!src) return null
  const profile = src.profileId ? (profiles.find((p) => p.id === src.profileId) ?? null) : null
  const resolved = resolveProfile(profile, defaults)
  return {
    options: resolved.options,
    extraArgs: resolved.extraArgs || undefined,
    collectionOutputTemplate: resolved.outputTemplate || undefined
  }
}
