import { type DownloadMeta, type MediaKind } from '@shared/ipc'
import { newId } from '../lib/id'
import { youtubeId } from '../lib/urlHelpers'
import { type AddOptions, type DownloadItem } from './downloadTypes'

// Placeholder channel shown while metadata is still being fetched. Tracked as a
// constant so the meta/error/done handlers can recognise and clear it instead of
// letting it stick forever when a probe returns no channel (SR6).
export const RESOLVING = 'Resolving…'

/**
 * Build a fresh queued DownloadItem from a URL + options. Pure (no store access)
 * so addFromUrl and addMany share it. If the caller already probed the URL, its
 * metadata is carried as probedMeta so main can skip a redundant probe (audit P2).
 */
export function buildItem(
  url: string,
  kind: MediaKind,
  quality: string,
  opts?: AddOptions
): DownloadItem {
  const probedMeta: DownloadMeta | undefined =
    opts?.title || opts?.channel || opts?.durationLabel
      ? { title: opts?.title, channel: opts?.channel, durationLabel: opts?.durationLabel }
      : undefined
  // A future scheduled time parks the item as 'saved' until its moment arrives;
  // a past/absent time starts it queued as usual.
  const scheduledFor =
    opts?.scheduledFor && opts.scheduledFor > Date.now() ? opts.scheduledFor : undefined
  return {
    id: newId('item'),
    url,
    title: opts?.title ?? titleFromUrl(url),
    channel: opts?.channel ?? RESOLVING,
    durationLabel: opts?.durationLabel,
    thumbnail: opts?.thumbnail,
    kind,
    quality,
    status: scheduledFor ? 'saved' : 'queued',
    progress: 0,
    formatId: opts?.format?.id,
    formatHasAudio: opts?.format?.hasAudio,
    options: opts?.options,
    extraArgs: opts?.extraArgs,
    trim: opts?.trim,
    scheduledFor,
    incognito: opts?.incognito,
    collection: opts?.collection,
    collectionOutputTemplate: opts?.collectionOutputTemplate,
    mediaItemId: opts?.mediaItemId,
    probedMeta
  }
}

export function titleFromUrl(url: string): string {
  const id = youtubeId(url)
  if (id) return `YouTube video (${id})`
  try {
    const host = new URL(url).hostname
    if (host) return `${host} download`
  } catch {
    /* not a URL */
  }
  return 'New download'
}
