import { describe, test, expect } from 'vitest';
import { parseProgress, buildYtDlpArgs } from './transcribe.js';

describe('parseProgress', () => {
  // Real lines captured from the bundled whisper-cli 1.9.1 (-pp / --print-progress).
  test('matches a real whisper.cpp progress line', () => {
    expect(parseProgress('whisper_print_progress_callback: progress =  79%')).toBe(79);
  });

  test('clamps whisper.cpp overshoot (>100%) to 100', () => {
    // whisper.cpp legitimately prints e.g. `progress = 159%` / `250%` on short audio.
    expect(parseProgress('whisper_print_progress_callback: progress = 250%')).toBe(100);
  });

  test('returns the last progress when a chunk has several lines', () => {
    const chunk = 'progress =  30%\nprogress =  60%\nprogress =  90%\n';
    expect(parseProgress(chunk)).toBe(90);
  });

  test('returns null for a chunk with no progress line', () => {
    expect(parseProgress('output_txt: saving output to out.txt')).toBeNull();
  });
});

describe('buildYtDlpArgs', () => {
  const fmt = (args: string[]) => args[args.indexOf('-f') + 1]!;

  test('guarantees an audio track (combined-or-merge selector), not a silent video-only mp4', () => {
    const f = fmt(buildYtDlpArgs('/tmp/v.mp4', {}));
    expect(f).toContain('[acodec!=none]'); // prefer a combined format that HAS audio
    expect(f).toContain('bv*+ba'); // else merge best video + best audio → audio guaranteed
    // the old selector grabbed the best mp4, which on IG DASH is video-only (silent)
    expect(f).not.toBe('mp4/best');
  });

  test('points yt-dlp at the bundled ffmpeg dir for merging when given a path', () => {
    const args = buildYtDlpArgs('/tmp/v.mp4', { ffmpegPath: '/App/Resources/bin/ffmpeg' });
    const i = args.indexOf('--ffmpeg-location');
    expect(i).toBeGreaterThan(-1);
    expect(args[i + 1]).toBe('/App/Resources/bin');
  });

  test('appends --cookies only when a cookies file is provided', () => {
    expect(buildYtDlpArgs('/tmp/v.mp4', {})).not.toContain('--cookies');
    expect(buildYtDlpArgs('/tmp/v.mp4', { cookiesFile: '/tmp/c.txt' })).toContain('/tmp/c.txt');
  });
});
