import { mkdtemp, writeFile, readFile } 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 extractMp3FromVideoBytes(videoBytes: Uint8Array): Promise<Uint8Array | null> {
	const tmpBase = await mkdtemp(join(tmpdir(), 'recipe-ai-audio-'));
	const inputPath = join(tmpBase, 'input.mp4');
	const outputPath = join(tmpBase, 'audio.mp3');
	await writeFile(inputPath, videoBytes);
	try {
		await execFile('ffmpeg', [
			'-hide_banner',
			'-loglevel', 'error',
			'-y',
			'-i', inputPath,
			'-vn',
			'-ar', '44100',
			'-ac', '1',
			'-b:a', '128k',
			outputPath,
		], { timeout: 30_000 });
		const buf = await readFile(outputPath);
		return new Uint8Array(buf);
	} catch {
		return null;
	}
}
