#!/usr/bin/env raku
use v6.d;

use FFmpegProgressBar;
use FFmpegProgressBar::ProgressSnapshot;

my $input-file = 'test.mkv';
my $output-file = 't/output-progress-test.mp4';

die "test.mkv not found" unless $input-file.IO.e;

my $p = FfmpegProgress.new;

say "Starting encoding of $input-file -> $output-file";
say "Will quit at 65% completion";
say "-" x 50;

my $running = True;

# Run encoding in a separate thread so we can poll progress
my $promise = start {
    $p.run('-i', $input-file, '-c:v', 'libx264', '-preset', 'fast', '-y', $output-file);
};

# Poll progress every 100ms
loop {
    if !$promise.status eq 'Running' {
        last;
    }
    
    my $snapshot = $p.get-progress();
    
    say sprintf("Progress: %5.1f%% | Frame: %s/%s | FPS: %5.1f | Speed: %.2fx | ETA: %s",
        $snapshot.percent,
        $snapshot.frame-count,
        $snapshot.total-frames > 0 ?? $snapshot.total-frames !! '?',
        $snapshot.fps,
        $snapshot.speed,
        $snapshot.eta.defined ?? sprintf('%.0fs', $snapshot.eta) !! 'calculating...'
    );
    
    # Quit at 65%
    if $snapshot.percent >= 65 {
        say "\nReached 65% - quitting!";
        $p.quit();
        last;
    }
    
    # Also quit if completed or failed
    if $snapshot.is-complete || $snapshot.is-failed {
        say "\nEncoding finished!";
        last;
    }
    
    sleep 0.1;
}

# Wait for the process to finish
await $promise;

say "-" x 50;
say "Done! Output saved to: $output-file";

# Show final stats
my $final = $p.get-progress();
say "Final: {$final.summary}";