import { existsSync } from 'fs'
import { getFfmpegPath, getFfprobePath } from './binaries'
import { execFileAsync } from './lib/exec'
import { VERSION_TIMEOUT_MS } from './constants'
import type { FfmpegVersionResult } from '@shared/ipc'

/**
 * Read the version token from an ffmpeg/ffprobe binary. Both print a first line
 * of the form "<tool> version <VERSION> Copyright ..." (e.g.
 * "ffmpeg version 6.1.1-full_build-www.gyan.dev Copyright ..."), so we return the
 * token after "version". Resolves null if the binary is absent, errors, times
 * out, or the line doesn't parse — Settings then shows "not found" instead of
 * failing. Unlike yt-dlp these are never self-updated, so there's no update path.
 */
async function readToolVersion(path: string): Promise<string | null> {
  if (!existsSync(path)) return null
  const r = await execFileAsync(path, ['-version'], { timeout: VERSION_TIMEOUT_MS })
  if (!r.ok) return null
  const firstLine = r.stdout.split('\n', 1)[0] ?? ''
  const m = firstLine.match(/version\s+(\S+)/i)
  return m?.[1] ?? null
}

/** Versions of the managed ffmpeg + ffprobe, read in parallel for the Settings panel. */
export async function getFfmpegVersions(): Promise<FfmpegVersionResult> {
  const [ffmpeg, ffprobe] = await Promise.all([
    readToolVersion(getFfmpegPath()),
    readToolVersion(getFfprobePath())
  ])
  return { ffmpeg, ffprobe }
}
