import type { MediaProfile, MediaKind, DownloadOptions } from './ipc'

/**
 * The global defaults a Media Profile can override — exactly the fields a
 * collection download would otherwise pull from Settings.
 */
export interface ProfileDefaults {
  kind: MediaKind
  videoQuality: string
  audioQuality: string
  options: DownloadOptions
  /** Settings.collectionOutputTemplate — the global collection folder layout */
  outputTemplate: string
}

/** The resolved per-download values a Source's profile (or the globals) produce. */
export interface ResolvedProfile {
  kind: MediaKind
  quality: string
  options: DownloadOptions
  /** collection folder layout ('' = the built-in default), or the profile override */
  outputTemplate: string
  /** extra yt-dlp args from the profile ('' when none) */
  extraArgs: string
}

/**
 * Resolve a download's effective settings for a Library source: **profile →
 * global default**, field by field. A `null`/`undefined` profile (source not
 * pointed at one, or a dangling id) yields the pure global defaults. The quality
 * default follows the resolved kind, so an audio-kind profile without its own
 * quality picks up the global AUDIO default (not video).
 *
 * Lives in `@shared` because both the renderer's enqueue path (which needs the
 * resolved kind/quality for the queued item) and any main-side use share this
 * one precedence rule. Pure — unit-tested in test/profileResolve.test.ts.
 */
export function resolveProfile(
  profile: MediaProfile | null | undefined,
  defaults: ProfileDefaults
): ResolvedProfile {
  const kind = profile?.kind ?? defaults.kind
  const globalQuality = kind === 'audio' ? defaults.audioQuality : defaults.videoQuality
  return {
    kind,
    quality: profile?.quality ?? globalQuality,
    options: profile?.options ?? defaults.options,
    outputTemplate: profile?.outputTemplate ?? defaults.outputTemplate,
    extraArgs: profile?.extraArgs ?? ''
  }
}
