import { existsSync } from 'fs'
import path from 'path'
import { config } from '../../config/app.config'

export type YtdlpParams = {
  url: string
  uuid: string
  format: string
  quality: string
  subtitles: boolean
  extraArgs: string | null
}

export function buildYtdlpArgs(params: YtdlpParams): string[] {
  const { url, uuid, format, quality, subtitles, extraArgs } = params
  const outputTemplate = path.join(config.STORAGE_PATH, `${uuid}.%(ext)s`)

  const args: string[] = ['--no-playlist', '-o', outputTemplate]

  const ffmpegBin = path.join(config.BIN_DIR, 'ffmpeg')
  if (existsSync(ffmpegBin)) {
    args.push('--ffmpeg-location', ffmpegBin)
  }

  if (quality !== 'best') {
    const height = quality.replace('p', '')
    args.push('-f', `${format}[height<=?${height}]+bestaudio/best[height<=?${height}]`)
  }

  if (subtitles) {
    args.push('--write-sub', '--sub-lang', 'fr,en')
  }

  if (extraArgs) {
    try {
      const extra = JSON.parse(extraArgs) as string[]
      args.push(...extra)
    } catch {
      // malformed extraArgs — skip silently
    }
  }

  args.push(url)
  return args
}
