import { execFileNoThrow } from "../utils/execFileNoThrow.js";

export interface ConverterCapabilities {
  /** Always true — sharp/file-type available as npm deps */
  imageConverter: boolean;
  /** Always true — ffmpeg-static available as npm dep */
  audioVideoConverter: boolean;
  /** True only if pandoc or libreoffice binary responds with status 0 */
  docConverter: boolean;
  /** Always true — xlsx/csv-parse available as npm deps */
  dataConverter: boolean;
}

let cachedCapabilities: ConverterCapabilities | null = null;

async function probe(): Promise<ConverterCapabilities> {
  const [pandocResult, libreofficeResult] = await Promise.all([
    execFileNoThrow("pandoc", ["--version"]),
    execFileNoThrow("libreoffice", ["--version"]),
  ]);

  return {
    imageConverter: true,
    audioVideoConverter: true,
    docConverter: pandocResult.status === 0 || libreofficeResult.status === 0,
    dataConverter: true,
  };
}

export function converterCapabilitiesService() {
  return {
    async get(): Promise<ConverterCapabilities> {
      if (cachedCapabilities === null) {
        cachedCapabilities = await probe();
      }
      return cachedCapabilities;
    },
  };
}
