#!/usr/bin/perl
use strict;
use warnings;
use Tk;
use File::Spec;
use File::Basename;
use File::Copy;
use File::Path qw(make_path);
use feature "say";

my @dir_stack = ('.');  # Stack to store directories navigated
my ($selected_file, $selected_dir, @contents, $text);
$selected_file= shift;
#stop resource conflict if called from another
use POSIX qw(close);
for my $fd (3 .. 1024) {
    POSIX::close($fd);
}
my $save_directory = "EXTRACTED";
my $in_time = "00:00:00";
my $out_time = "00:01:00";
my $fps = "1";  # frames per second for extraction
my $extract_audio = 1;
my $extract_video = 1;
my $video_duration = "";

my $mw = MainWindow->new;
$mw->title("Video Section & Frames Extractor");
$mw->geometry("1200x1000+100+100");
my $font = '{Helvetica} 16';

my $label = $mw->Label(-font => $font, -text => "Browse and select a video file:", -width => 40)->grid(qw/-row 0 -column 0 -sticky nsew/);

my $frame = $mw->Frame()->grid(qw/-row 2 -column 0 -sticky w/);
my $frame2 = $mw->Frame()->grid(qw/-row 4 -column 0 -sticky w/);
my $frame3 = $mw->Frame()->grid(qw/-row 2 -column 1 -rowspan 6 -columnspan 2 -sticky nsew/);

my $button = $mw->Button(-font => $font, -text => 'GO UP', -justify => 'left', -width => 8, -command => sub { &GO_UP })->grid(qw/-row 3 -column 0 -sticky w/);
$button = $mw->Button(-font => $font, -text => 'QUIT', -justify => 'left', -width => 8, -command => sub { $mw->destroy() })->grid(qw/-row 5 -column 0 -sticky w/);

my $listbox = $frame->Scrolled('Listbox', -font => $font, -scrollbars => 'se', -width => 40, -height => 20)->grid(qw/-row 0 -column 0 -sticky w/);
my $message_box = $frame2->Scrolled('Listbox', -font => $font, -scrollbars => 'se', -width => 40, -height => 8)->grid(qw/-row 0 -column 0 -sticky w/);
$listbox->bind('<Double-Button-1>', \&select_item);

############ Right panel controls ############

$label = $frame3->Label(-font => $font, -text => "Save directory:", -width => 16)->grid(qw/-row 0 -column 0 -sticky nsew/);
my $entry = $frame3->Entry(-font => $font, -textvariable => \$save_directory, -width => 30)->grid(qw/-row 0 -column 1 -sticky nsew/);

$label = $frame3->Label(-font => $font, -text => "Selected file:", -width => 16)->grid(qw/-row 1 -column 0 -sticky nsew/);
$entry = $frame3->Entry(-font => $font, -textvariable => \$selected_file, -width => 30)->grid(qw/-row 1 -column 1 -sticky nsew/);

$label = $frame3->Label(-font => $font, -text => "In time (HH:MM:SS):", -width => 16)->grid(qw/-row 2 -column 0 -sticky nsew/);
$entry = $frame3->Entry(-font => $font, -textvariable => \$in_time, -width => 30)->grid(qw/-row 2 -column 1 -sticky nsew/);

$label = $frame3->Label(-font => $font, -text => "Out time (HH:MM:SS):", -width => 16)->grid(qw/-row 3 -column 0 -sticky nsew/);
$entry = $frame3->Entry(-font => $font, -textvariable => \$out_time, -width => 30)->grid(qw/-row 3 -column 1 -sticky nsew/);

$label = $frame3->Label(-font => $font, -text => "Frames FPS:", -width => 16)->grid(qw/-row 4 -column 0 -sticky nsew/);
$entry = $frame3->Entry(-font => $font, -textvariable => \$fps, -width => 30)->grid(qw/-row 4 -column 1 -sticky nsew/);

$label = $frame3->Label(-font => $font, -text => "Extract:", -width => 16)->grid(qw/-row 5 -column 0 -sticky nsew/);
my $opt_frame = $frame3->Frame()->grid(qw/-row 5 -column 1 -sticky w/);
$opt_frame->Checkbutton(-font => $font, -text => "Audio", -variable => \$extract_audio)->pack(-side => 'left', -padx => 5);
$opt_frame->Checkbutton(-font => $font, -text => "Video", -variable => \$extract_video)->pack(-side => 'left', -padx => 5);

$label = $frame3->Label(-font => $font, -text => "Duration:", -width => 16)->grid(qw/-row 6 -column 0 -sticky nsew/);
$entry = $frame3->Entry(-font => $font, -textvariable => \$video_duration, -width => 25, -state => 'readonly')->grid(qw/-row 6 -column 1 -sticky nsew/);

$button = $frame3->Button(-font => $font, -text => 'Extract Section', -justify => 'left', -width => 22,
    -command => sub { &extract_section })->grid(qw/-row 7 -column 0 -columnspan 2 -sticky nsew/);

$button = $frame3->Button(-font => $font, -text => 'Extract Frames', -justify => 'left', -width => 22,
    -command => sub { &extract_frames })->grid(qw/-row 8 -column 0 -columnspan 2 -sticky nsew/);

&refresh_listbox;
MainLoop;

sub refresh_listbox {
    my $dir = $dir_stack[-1];
    $listbox->delete(0, 'end');

    opendir(my $dh, $dir) or do {
        log_msg("Can't open $dir: $!");
        return;
    };
    @contents = readdir($dh);
    closedir($dh);
    @contents = sort { lc($a) cmp lc($b) } @contents;

    foreach my $item (@contents) {
        next if $item =~ /^\./;  # skip hidden
        my $path = File::Spec->catfile($dir, $item);
        if (-d $path) {
            $listbox->insert('end', $item);
            $listbox->itemconfigure('end', -foreground => 'blue');
        } elsif ($item =~ /\.(mp4|mkv|avi|mov|wmv|flv|webm|m4v)$/i) {
            $listbox->insert('end', $item);
            $listbox->itemconfigure('end', -foreground => 'darkgreen');
        }
    }
}

sub select_item {
    my $selection = $listbox->get('active');
    return unless defined $selection;
    my $path = File::Spec->catfile($dir_stack[-1], $selection);

    if (-d $path) {
        push @dir_stack, $path;
        $selected_dir = $path;
        log_msg("Selected directory: $selected_dir");
        refresh_listbox();
    } elsif (-f $path) {
        $selected_file = $path;
        log_msg("Selected file: $selected_file");
        get_video_duration($selected_file);
    }
}

sub GO_UP {
    pop @dir_stack if @dir_stack > 1;
    refresh_listbox();
    log_msg("Went up to: " . $dir_stack[-1]);
}

sub log_msg {
    my $msg = shift;
    $message_box->insert('end', $msg);
    $message_box->see('end');
    say $msg;  # also to terminal
}

sub ensure_dir {
    my $dir = shift;
    unless (-d $dir) {
        make_path($dir) or die "Cannot create directory $dir: $!";
        log_msg("Created directory: $dir");
    }
}

sub get_video_duration {
    my $file = shift;
    return unless $file && -f $file;

    my $cmd = qq{ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$file"};
    my $duration_sec = `$cmd` || "";
    chomp $duration_sec;

    if ($duration_sec =~ /^\d+\.?\d*$/) {
        my $sec = int($duration_sec + 0.5);  # round
        my $h = int($sec / 3600);
        my $m = int(($sec % 3600) / 60);
        my $s = $sec % 60;
        $video_duration = sprintf("%02d:%02d:%02d (%.1f s)", $h, $m, $s, $duration_sec);
        log_msg("Duration: $video_duration");
    } else {
        $video_duration = "unknown";
        log_msg("Could not determine duration");
    }
}

sub extract_section {
    unless ($selected_file && -f $selected_file) {
        log_msg("ERROR: No valid video file selected.");
        return;
    }
    unless ($in_time && $out_time) {
        log_msg("ERROR: Please set In time and Out time.");
        return;
    }

    ensure_dir($save_directory);
    my $base = basename($selected_file);
    $base =~ s/\.[^.]+$//;
    my $timesafe = $in_time;
    $timesafe =~ s/[:]/_/g;
    my $outsafe = $out_time;
    $outsafe =~ s/[:]/_/g;

    my ($ext, $codec_opts, $label);
    if ($extract_video && $extract_audio) {
        $ext = "mp4";
        $codec_opts = "-c:v libx264 -crf 23 -c:a aac -strict experimental";
        $label = "video+audio";
    } elsif ($extract_video) {
        $ext = "mp4";
        $codec_opts = "-c:v libx264 -crf 23 -an";
        $label = "video-only";
    } elsif ($extract_audio) {
        $ext = "m4a";
        $codec_opts = "-vn -c:a aac -strict experimental";
        $label = "audio-only";
    } else {
        log_msg("ERROR: Select at least one of Audio or Video.");
        return;
    }

    my $output = File::Spec->catfile($save_directory, "${base}_section_${timesafe}_${outsafe}_${label}.$ext");

    log_msg("Extracting $label section from $in_time to $out_time ...");
    log_msg("Output: $output");

    my $ffmpeg_command = qq{ffmpeg -y -i "$selected_file" -ss $in_time -to $out_time $codec_opts "$output" 2>&1};
    log_msg("Running: $ffmpeg_command");

    my $ff_output = `$ffmpeg_command`;
    my $status = $?;
    log_msg("--- ffmpeg output ---");
    for my $line (split /\n/, $ff_output) {
        log_msg($line) if $line =~ /\S/;
    }
    log_msg("--- end ffmpeg ---");

    if ($status == 0 && -f $output) {
        log_msg("SUCCESS: Section extracted to $output");
    } elsif ($status == 0) {
        log_msg("WARNING: ffmpeg exited 0 but output file missing");
    } else {
        log_msg("ERROR: ffmpeg failed with status $status");
    }
}

sub extract_frames {
    unless ($selected_file && -f $selected_file) {
        log_msg("ERROR: No valid video file selected.");
        return;
    }

    ensure_dir($save_directory);
    my $base = basename($selected_file);
    $base =~ s/\.[^.]+$//;
    my $frames_dir = File::Spec->catfile($save_directory, "${base}_frames");
    ensure_dir($frames_dir);

    my $pattern = File::Spec->catfile($frames_dir, "frame_%04d.png");

    log_msg("Extracting frames at $fps fps ...");
    log_msg("To directory: $frames_dir");
    log_msg("Pattern: $pattern");

    my $time_opts = "";
    if ($in_time && $out_time && $in_time ne "00:00:00") {
        $time_opts = "-ss $in_time -to $out_time";
    }

    my $ffmpeg_command = qq{ffmpeg -y -i "$selected_file" $time_opts -vf fps=$fps "$pattern" 2>&1};
    log_msg("Running: $ffmpeg_command");

    # Capture all output so we can see why nothing was written
    my $output = `$ffmpeg_command`;
    my $status = $?;
    log_msg("--- ffmpeg output ---");
    for my $line (split /\n/, $output) {
        log_msg($line) if $line =~ /\S/;
    }
    log_msg("--- end ffmpeg ---");

    # Count what was actually created
    my @frames = glob(File::Spec->catfile($frames_dir, "frame_*.png"));
    my $count = scalar @frames;

    if ($status == 0 && $count > 0) {
        log_msg("SUCCESS: $count frames extracted to $frames_dir");
    } elsif ($status == 0) {
        log_msg("WARNING: ffmpeg exited 0 but no frames were written (check times / fps)");
    } else {
        log_msg("ERROR: ffmpeg failed with status $status");
    }
}
