export interface VideoGenerationOptions {
  negativePrompt?: string;
  size?: string; // "WxH"
  numFrames?: number;
  fps?: number;
  steps?: number;
  guidanceScale?: number;
  seed?: number; // -1 = random (omitted)
  initImage?: File | null; // image-to-video conditioning frame
}

// POST /v1/videos/sync (multipart; llama-swap routes by the `model` field).
// The response body IS the encoded clip — returns an object URL for <video>.
// Callers must URL.revokeObjectURL() the result when done with it.
export async function generateVideoSync(
  model: string,
  prompt: string,
  options: VideoGenerationOptions = {},
  signal?: AbortSignal
): Promise<{ url: string; mime: string; sizeBytes: number }> {
  const form = new FormData();
  form.set("model", model);
  form.set("prompt", prompt);
  if (options.negativePrompt) form.set("negative_prompt", options.negativePrompt);
  if (options.size) {
    const [w, h] = options.size.split("x").map(Number);
    if (w > 0 && h > 0) {
      // Both conventions: vLLM-Omni reads width/height, OpenAI-shaped
      // upstreams read size; they can never disagree.
      form.set("width", String(w));
      form.set("height", String(h));
      form.set("size", options.size);
    }
  }
  if (options.numFrames && options.numFrames > 0) form.set("num_frames", String(options.numFrames));
  if (options.fps && options.fps > 0) form.set("fps", String(options.fps));
  if (options.steps && options.steps > 0) form.set("num_inference_steps", String(options.steps));
  if (options.guidanceScale && options.guidanceScale > 0)
    form.set("guidance_scale", String(options.guidanceScale));
  if (options.seed !== undefined && options.seed >= 0) form.set("seed", String(options.seed));
  if (options.initImage) form.set("input_reference", options.initImage, options.initImage.name);

  const response = await fetch("/v1/videos/sync", {
    method: "POST",
    body: form,
    signal,
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Video API error: ${response.status} - ${errorText}`);
  }

  const blob = await response.blob();
  const mime = response.headers.get("Content-Type") || "video/mp4";
  return { url: URL.createObjectURL(blob), mime, sizeBytes: blob.size };
}
