import { spawn } from "child_process";
import { promises as fs } from "fs";
import { getVideoConfig } from "@/lib/generation/video-config";

/** Rasterize SVG to PNG. FFmpeg does not render embedded data-URL logos reliably. */
export async function rasterizeSvgToPng(
  svgPath: string,
  pngPath: string,
  size?: { width: number; height: number },
): Promise<boolean> {
  const cfg = getVideoConfig();
  const w = size?.width ?? 1024;
  const h = size?.height ?? 1024;

  return new Promise((resolve) => {
    const args = ["-y", "-i", svgPath, "-vf", `scale=${w}:${h}`, pngPath];

    const proc = spawn(cfg.ffmpegPath, args, { stdio: ["ignore", "pipe", "pipe"] });
    let stderr = "";

    proc.stderr.on("data", (chunk: Buffer) => {
      stderr += chunk.toString();
    });

    proc.on("error", () => resolve(false));

    proc.on("close", async (code) => {
      if (code !== 0) {
        console.warn("[PostSync] SVG rasterize failed:", stderr.slice(-200));
        resolve(false);
        return;
      }
      try {
        await fs.access(pngPath);
        resolve(true);
      } catch {
        resolve(false);
      }
    });
  });
}
