import type { DownloadProgress } from '@shared/ipc'
import { fmtBytes } from '@shared/format'

// yt-dlp progress-line parsing. Extracted from download.ts so it can be
// unit-tested without pulling in the electron import chain (L37). Byte/speed/ETA
// formatting lives in @shared/format — the one home for both sides of the IPC
// boundary; consumers import it directly.

function num(s?: string): number | undefined {
  if (!s || s === 'NA') return undefined
  const n = Number(s)
  return Number.isFinite(n) ? n : undefined
}

export function parseProgress(rest: string): DownloadProgress | null {
  const parts = rest.split('|')
  if (parts.length < 6) return null
  const [status, dl, total, totalEst, speed, eta] = parts
  const downloaded = num(dl)
  const totalBytes = num(total) ?? num(totalEst)
  let progress = 0
  if (totalBytes && downloaded != null) progress = Math.min(1, downloaded / totalBytes)
  return {
    status: status || 'downloading',
    progress,
    // Carry raw numbers across the IPC boundary; the renderer formats them for
    // display AND aggregates them (combined speed / longest ETA) without having
    // to re-parse a formatted string (H4).
    speedBytesPerSec: num(speed),
    etaSeconds: num(eta),
    sizeLabel: totalBytes ? fmtBytes(totalBytes) : undefined,
    // No (estimated) total → the % can never advance; flag it so the renderer
    // shows an indeterminate bar rather than a stuck 0% (L137).
    sizeUnknown: !totalBytes
  }
}
