import { mkdtemp, writeFile, readFile, readdir } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
import { execFile as _execFile } from 'node:child_process';

const execFile = promisify(_execFile);

export async function extractThumbnailsFromVideoBytes(
  videoBytes: Uint8Array,
  maxFrames: number | null = 8,
  fps = 2,
  maxWidth = 640,
): Promise<Uint8Array[]> {
  const tmpBase = await mkdtemp(join(tmpdir(), 'recipe-ai-'));
  const inputPath = join(tmpBase, 'input.mp4');
  await writeFile(inputPath, videoBytes);

  const pattern = join(tmpBase, 'frame-%02d.jpg');
  try {
    // Extract frames at specified fps; if maxFrames <= 0 or null, extract full video
    const args = [
      '-hide_banner',
      '-loglevel', 'error',
      '-y',
      '-i', inputPath,
      '-vf', `fps=${fps},scale=${maxWidth}:-1:force_original_aspect_ratio=decrease`,
      '-q:v', '2',
    ];
    if (maxFrames && maxFrames > 0) {
      args.push('-vframes', String(maxFrames));
    }
    args.push(pattern);
    await execFile('ffmpeg', args, { timeout: 120_000 });
  } catch {
    return [];
  }

  try {
    const files = (await readdir(tmpBase))
      .filter((f) => /^frame-\d+\.jpg$/i.test(f))
      .sort();
    const results: Uint8Array[] = [];
    for (const f of files) {
      const buf = await readFile(join(tmpBase, f));
      results.push(new Uint8Array(buf));
    }
    return results;
  } catch {
    return [];
  }
}


