#!/usr/bin/perl
# Fixed mix frames generator
# Reads a CSV of image,w,h,x,y (no header assumed) and creates progressive blend frames
# between consecutive images, with the selected number of mix steps.
# Always uses a transparent canvas of the user-specified size.
# Images are scaled to the w/h given in the CSV (if different from actual size) for both
# positioning and blending. If w/h missing or zero in CSV, actual image size is used.

use strict;
use warnings;
use Tk;
use File::Spec;
use Math::Round;
use Image::Size qw/imgsize/;
use Image::Imlib2;
use Text::CSV_XS;
use feature "say";

my @dir_stack = ('.');
my $selected_file = "";
my $selected_dir;
my @contents;
my $text;
my $frames = 4;               # number of steps (0 to $frames inclusive = $frames+1 frames per transition)
my @temp;
my @dope;
my $file;
my $save_directory = "MIXES";
my $canvas_width = 1920;
my $canvas_height = 1080;
my @mix_frames = qw(3 4 6 8);
my $num = 0;

my $mw = MainWindow->new;
$mw->title("MAKE MIX FRAMES");
$mw->geometry("1100x860+100+100");

my $frame = $mw->Frame()->grid(qw/ -row 2 -column 0  -sticky w/);
my $frame3 = $mw->Frame()->grid(qw/ -row 2 -column 1  -sticky w/);
my $frame2 = $mw->Frame()->grid(qw/ -row 12 -column 0 -sticky w/);

my $listbox = $frame->Scrolled('Listbox', -font => '{Helvetica} 20', -scrollbars => 'se', -width => 30)
    ->grid(qw/ -row 0 -column 0 -sticky w/);
my $listbox2 = $frame2->Scrolled('Listbox', -font => '{Helvetica} 20', -scrollbars => 'se', -width => 30, -height => 6)
    ->grid(qw/ -row 0 -column 0  -sticky w/);

$listbox->bind('<Double-Button-1>', \&select_item);

my $button = $frame->Button(-font => '{Helvetica} 15', -text => 'UP', -width => 4, -command => \&go_up)
    ->grid(qw/ -row 10 -column 0 -sticky w/);

my $label = $frame3->Label(-font => '{Helvetica} 20',
    -text => "double click select image,whxy file.\nCanvas is always transparent,\nsized to the values below.",
    -width => 30)->grid(qw/ -row 10 -column 0 -columnspan 4 -sticky n/);

$label = $frame3->Label(-font => '{Helvetica} 15', -text => "save images directory:", -width => 18, -justify => 'center')
    ->grid(qw/ -row 12 -column 0 -sticky n/);
my $entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$save_directory, -width => 10, -justify => "center")
    ->grid(qw/ -row 12 -column 1 -sticky w/);

$entry = $frame3->Label(-font => '{Helvetica} 15', -text => 'mix frames', -width => 10, -justify => "center")
    ->grid(qw/ -row 13 -column 0 -sticky n/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$frames, -width => 10, -justify => "center")
    ->grid(qw/ -row 13 -column 1 -sticky w/);
$entry = $frame3->Button(-font => '{Helvetica} 15', -text => '-->', -width => 4, -justify => "left",
    -command => sub {
        $num = $num + 1;
        if ($num > 3) { $num = 0 }
        $frames = $mix_frames[$num];
    })->grid(qw/ -row 13 -column 2 -sticky w/);

$entry = $frame3->Label(-font => '{Helvetica} 15', -text => 'canvas width', -width => 12, -justify => "center")
    ->grid(qw/ -row 14 -column 0 -sticky n/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$canvas_width, -width => 10, -justify => "center")
    ->grid(qw/ -row 14 -column 1 -sticky w/);

$entry = $frame3->Label(-font => '{Helvetica} 15', -text => 'canvas height', -width => 12, -justify => "center")
    ->grid(qw/ -row 15 -column 0 -sticky n/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$canvas_height, -width => 10, -justify => "center")
    ->grid(qw/ -row 15 -column 1 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'image,whxy file', -justify => 'left', -width => 12,
    -command => sub { if (defined $selected_file) { $file = $selected_file; say $file; } })
    ->grid(qw/ -row 16 -column 0 -sticky w/);
$entry = $frame3->Entry(-font => '{Helvetica} 15', -textvariable => \$file, -width => 20, -justify => "left")
    ->grid(qw/ -row 16 -column 1 -columnspan 3 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'make mixes', -justify => 'center', -width => 12,
    -command => sub { &make_array() })->grid(qw/ -row 17 -column 0 -sticky w/);

$button = $frame3->Button(-font => '{Helvetica} 15', -text => 'EXIT', -justify => 'left', -width => 12,
    -command => sub { $mw->destroy() })->grid(qw/ -row 20 -column 0 -sticky w/);

&refresh_listbox;
MainLoop;

sub numerically {
    my ($a_num) = $a =~ /(\d+)/;
    my ($b_num) = $b =~ /(\d+)/;
    $a_num //= 0;
    $b_num //= 0;
    return $a_num <=> $b_num;
}

sub precheck {
    my @problems;
    my $skipped_xy = 0;

    # Basic inputs
    unless (defined $file && $file ne '' && -f $file && -r $file) {
        push @problems, "CSV file not set, missing, or not readable: " . ($file // "(none)");
    }
    my $base_w = $canvas_width + 0;
    my $base_h = $canvas_height + 0;
    if ($base_w <= 0 || $base_h <= 0) {
        push @problems, "canvas width and height must be > 0 (got ${base_w}x${base_h})";
    }
    unless (defined $frames && $frames =~ /^\d+$/ && $frames > 0) {
        push @problems, "mix frames must be a positive integer (got " . ($frames // "undef") . ")";
    }
    unless (defined $save_directory && $save_directory ne '') {
        push @problems, "save directory not set";
    }

    # If basic checks failed, report and stop
    if (@problems) {
        $listbox2->insert('end', "--- pre-check problems ---");
        $listbox2->insert('end', $_) for @problems;
        $listbox2->see('end');
        return 0;
    }

    # Parse CSV and validate each image
    @temp = ();
    my $csv = Text::CSV_XS->new({ binary => 1, auto_diag => 1 });
    open(my $fh, '<', $file) or do {
        $listbox2->insert('end', "Can't open $file: $!");
        return 0;
    };

    my $line_num = 0;
    while (my $row = $csv->getline($fh)) {
        $line_num++;
        next unless @$row && (@$row % 2 == 0);
        my %values = @$row;
        next unless defined $values{image} && $values{image} ne '';
        next unless defined $values{w} && defined $values{h};

        if (!defined $values{x} || $values{x} eq '' || !defined $values{y} || $values{y} eq '') {
            $skipped_xy++;
            next;
        }

        my $img = $values{image};
        my $w = ($values{w} || 0) + 0;
        my $h = ($values{h} || 0) + 0;
        my $x = $values{x} + 0;
        my $y = $values{y} + 0;

        unless (-f $img && -r $img) {
            push @problems, "line $line_num: image not found or not readable: $img";
            next;
        }
        if ($w <= 0 || $h <= 0) {
            push @problems, "line $line_num: w/h must be > 0 for $img (got ${w}x${h})";
            next;
        }

        push @temp, {
            image => $img,
            w     => $w,
            h     => $h,
            x     => $x,
            y     => $y,
        };
    }
    close $fh;

    if (@problems) {
        $listbox2->insert('end', "--- pre-check problems ---");
        $listbox2->insert('end', $_) for @problems;
        $listbox2->see('end');
        return 0;
    }

    if (@temp < 2) {
        $listbox2->insert('end', "! need at least 2 valid images to mix (found " . @temp . ") !");
        $listbox2->see('end');
        return 0;
    }

    $listbox2->insert('end', "pre-check OK: " . @temp . " images, canvas ${base_w}x${base_h}, $frames mix steps");
    $listbox2->see('end');

    # Return the skip count so it can be reported at the end
    return $skipped_xy + 1;   # +1 so 0 skips still returns true
}

sub make_array {
    say "here make array";
    $listbox2->delete('0', 'end');

    # Pre-check everything before starting the (potentially long) frame generation
    my $skipped_xy = precheck() - 1;
    unless ($skipped_xy >= 0) {
        $text = "! pre-check failed - aborting !";
        $listbox2->insert('end', $text);
        $listbox2->see('end');
        return;
    }

    &check_dir;
    my $ct = 0;
    # @temp is already populated by precheck()
    my $base_w = $canvas_width + 0;
    my $base_h = $canvas_height + 0;

    # Always transparent canvas of the specified size
    my $base_img = Image::Imlib2->new_transparent($base_w, $base_h);
    $text = "made transparent canvas ${base_w}x${base_h}";
    $listbox2->insert('end', $text);

    # Determine use sizes (CSV if provided, else actual) and compute positions
    @dope = ();
    for my $i (0 .. $#temp) {
        my $img_path = $temp[$i]{image};
        unless (-f $img_path) {
            $text = "missing image: $img_path";
            $listbox2->insert('end', $text);
            next;
        }
        my $loaded = Image::Imlib2->load($img_path);
        my $actual_w = $loaded->width;
        my $actual_h = $loaded->height;
        my $use_w = ($temp[$i]{w} > 0) ? $temp[$i]{w} : $actual_w;
        my $use_h = ($temp[$i]{h} > 0) ? $temp[$i]{h} : $actual_h;

        $dope[$i] = {
            image => $img_path,
            w     => $use_w,
            h     => $use_h,
            x     => (($base_w - $use_w) / 2) + $temp[$i]{x},
            y     => (($base_h - $use_h) / 2) + $temp[$i]{y},
        };
        if ($use_w != $actual_w || $use_h != $actual_h) {
            $text = "will scale $img_path from ${actual_w}x${actual_h} to ${use_w}x${use_h}";
            $listbox2->insert('end', $text);
        }
    }

    my $n_images = @dope;
    if ($n_images < 2) {
        $text = "! need at least 2 images to mix !";
        $listbox2->insert('end', $text);
        return;
    }

    my $frame_count = 0;
    for my $i (0 .. $n_images - 2) {
        my $img1 = $dope[$i];
        my $img2 = $dope[$i + 1];
        # For the first pair start at n=0 (include 100% of first image).
        # For later pairs start at n=1 so we don't repeat the 100% frame
        # that was already written as the end of the previous transition.
        my $start_n = ($i == 0) ? 0 : 1;
        for my $n ($start_n .. $frames) {
            # alpha1 from 255 -> 0, alpha2 from 0 -> 255
            my $alpha1 = int(255 * ($frames - $n) / $frames);
            my $alpha2 = int(255 * $n / $frames);

            # Start from a fresh copy of the base each time
            my $frame = $base_img->clone;
            $frame->will_blend(1);

            # Blend first image at its position with alpha1 (scaled to CSV size if needed)
            blend_with_alpha($frame, $img1->{image}, $alpha1, $img1->{x}, $img1->{y}, $img1->{w}, $img1->{h});

            # Blend second image at its position with alpha2
            blend_with_alpha($frame, $img2->{image}, $alpha2, $img2->{x}, $img2->{y}, $img2->{w}, $img2->{h});

            my $out = sprintf("%s/images/mix_%02d_%02d.png", $save_directory, $i, $n);
            $frame->save($out);
            $frame_count++;
            $text = "saved $out (a1=$alpha1 a2=$alpha2)";
            $listbox2->insert('end', $text);
            $listbox2->see('end');
            $mw->update;
        }
    }

    $text = "done - created $frame_count frames";
    $listbox2->insert('end', $text);
    if ($skipped_xy) {
        $text = "warning: skipped $skipped_xy line(s) with missing/empty x or y";
        $listbox2->insert('end', $text);
    }
    $listbox2->see('end');
    say "done";
}

# Sets non-zero-alpha pixels of the (optionally scaled) image to the given alpha, then blends it onto $dest at (dx,dy)
sub blend_with_alpha {
    my ($dest, $file, $new_alpha, $dx, $dy, $target_w, $target_h) = @_;
    return unless -f $file;
    my $img = Image::Imlib2->load($file);
    my $width  = $img->width;
    my $height = $img->height;

    # Scale to target size from CSV if different
    if ($target_w > 0 && $target_h > 0 && ($width != $target_w || $height != $target_h)) {
        $img = $img->create_scaled_image($target_w, $target_h);
        $width  = $target_w;
        $height = $target_h;
    }

    $img->will_blend(0);
    $img->has_alpha(1);

    for my $y (0 .. $height - 1) {
        for my $x (0 .. $width - 1) {
            my ($red, $green, $blue, $alpha) = $img->query_pixel($x, $y);
            if ($alpha != 0) {
                $img->set_colour($red, $green, $blue, $new_alpha);
                $img->draw_point($x, $y);
            }
        }
    }
    $img->will_blend(1);

    # Blend onto destination (merge_alpha=1 so alpha is respected)
    $dest->blend($img, 1, 0, 0, $width, $height, $dx, $dy, $width, $height);
}

sub check_dir {
    unless (-d "./$save_directory") { mkdir "./$save_directory" }
    unless (-d "./$save_directory/images") {
        mkdir "./$save_directory/images";
        $text = "made directory $save_directory/images";
    }
    $listbox2->insert('end', $text) if $text;
    return;
}

sub refresh_listbox {
    my $dir = $dir_stack[-1];
    $listbox->delete(0, 'end');
    opendir(my $dh, $dir) or die "Can't open $dir: $!";
    @contents = readdir($dh);
    closedir($dh);
    @contents = sort { lc($a) cmp lc($b) } @contents;
    foreach my $item (@contents) {
        next if $item =~ /^\./;
        my $path = File::Spec->catfile($dir, $item);
        if (-d $path) {
            $listbox->insert('end', $item);
            $listbox->itemconfigure('end', -foreground => 'blue');
        } elsif ($item =~ /\.(png|jpg|jpeg|list|csv)$/i) {
            $listbox->insert('end', $item);
        }
    }
}

sub select_item {
    my $selection = $listbox->get('active');
    my $path = File::Spec->catfile($dir_stack[-1], $selection);
    if (-d $path) {
        push @dir_stack, $path;
        refresh_listbox();
        $selected_dir = $path;
        $text = "Selected directory: $selected_dir";
        $listbox2->delete('0', 'end');
        $listbox2->insert('0', $text);
    } elsif (-f $path) {
        $selected_file = $path;
        $text = "selected file = $selected_file";
        $listbox2->insert('end', $text);
    }
    if ($selected_file eq "./BLANK.png") {
        $selected_file = "BLANK";
    }
    refresh_listbox();
}

sub go_up {
    pop @dir_stack if @dir_stack > 1;
    refresh_listbox();
}
