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

use lib 'lib';
use FFmpegProgressBar;

sub MAIN() {
    my $input-file = 't/myVideo_with_tone.mp4';
    my $output-file = 't/output-progress-test.mp4';

    die "myVideo_with_tone.mp4 not found" unless $input-file.IO.e;

    my $p = FfmpegProgress.new;

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

    my $quit-requested = False;

    my $promise = start {
        $p.run('-i', $input-file, '-c:v', 'libx264', '-preset', 'fast', '-y', $output-file);
    };

    loop {
        last if $promise.status ~~ Kept | Broken;
        
        my $snapshot = $p.get-progress();
        
        my $display-percent = do {
            my $tc = $snapshot.total-frames // 0;
            my $fc = $snapshot.frame-count // 0;
            if $tc > 0 {
                min(($fc / $tc * 100).Num, 100);
            } else {
                $snapshot.percent;
            }
        };
        
        say sprintf("Progress: %5.1f%% | Frame: %s/%s | FPS: %5.1f | Speed: %.2fx | Status: %s",
            $display-percent,
            $snapshot.frame-count // 0,
            $snapshot.total-frames // 0,
            $snapshot.fps // 0,
            $snapshot.speed // 0,
            $snapshot.status // 'unknown'
        );
        
        # Quit based on frame count when total-frames is known
        if $snapshot.total-frames.defined && $snapshot.total-frames > 0 
           && $snapshot.frame-count.defined {
            my $frame-percent = ($snapshot.frame-count / $snapshot.total-frames * 100);
            if $frame-percent >= 70 {
                say "\nReached 70% - quitting!";
                $p.quit();
                $quit-requested = True;
                last;
            }
        }
        
        if $snapshot.status eq 'completed' || $snapshot.status eq 'failed' || $snapshot.status eq 'aborted' {
            say "\nEncoding finished with status: {$snapshot.status}";
            last;
        }
        
        sleep 0.1;
    }

    await $promise;

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

    my $final = $p.get-progress();
    say "Final: {$final.summary}";
    say "Final status: {$final.status // 'unknown'}";
}