import "server-only";

import { getMediaProcessingConfig } from "@/lib/server/media-config";
import { runBinaryCommand } from "@/lib/ffmpeg/run-command";
import { MediaProcessingError } from "@/lib/server/media-errors";

interface RunFfprobeOptions {
  timeoutMs?: number;
  cwd?: string;
}

export async function runFfprobe(args: string[], options: RunFfprobeOptions = {}) {
  const config = getMediaProcessingConfig();
  return runBinaryCommand(config.ffprobePath, args, options);
}

export async function runFfprobeJson<T>(
  args: string[],
  options: RunFfprobeOptions = {}
): Promise<T> {
  const result = await runFfprobe(args, options);

  try {
    return JSON.parse(result.stdout) as T;
  } catch {
    throw new MediaProcessingError({
      message: "Failed to parse ffprobe JSON output.",
      code: "ffprobe_failure",
      statusCode: 500,
      details: {
        stdoutSample: result.stdout.slice(0, 1000)
      }
    });
  }
}
