#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use Tk;
use Tk::PNG;
use Tk::JPEG;
use File::Path qw(make_path);
use File::Basename qw(basename dirname);
use File::Spec;
use Cwd qw(abs_path);
use Image::Imlib2;

# Overlay scale visualizer + sequence generator
# Shows how a bigger / re-positioned overlay would look on a background,
# then generates the resized sequence from matching higher-res source images.
# Matches large images by the shared number in the filename, ignoring other text.

my $project_root = abs_path(shift // '.');

my $mw = MainWindow->new;
$mw->title('Overlay Scale Visualizer');
$mw->geometry('1400x900');
$mw->optionAdd('*Font', 'Helvetica 11');

# State
my $bg_csv;
my $overlay_csv;
my $bg_image_path;
my $overlay_image_path;
my $source_dir;
my $save_dir;
my $frames = 30;
my $fairing_on = 0;
my $fairing_front = 0;
my $fairing_back  = 0;
my $fairing_style = 'linear';

my %photo_cache;
my $resize_aspect = 1;
my %rect = (
    start_x => 80,  start_y => 80,  start_w => 300, start_h => 200,
    end_x   => 200, end_y   => 120, end_w   => 500, end_h   => 333,
);
my $resize_drag;
my $show_composite = 0;

my $bg_item;
my $start_img_item;
my $end_img_item;
my $start_rect_item;
my $end_rect_item;
my $scaled_photo;   # cached scaled preview

# UI
my $top = $mw->Frame()->pack(-side => 'top', -fill => 'x', -padx => 6, -pady => 4);

$top->Button(-text => 'Select Background CSV', -command => \&select_bg)->pack(-side => 'left', -padx => 3);
$top->Button(-text => 'Select Overlay CSV',    -command => \&select_overlay)->pack(-side => 'left', -padx => 3);
$top->Button(-text => 'Select Source Dir',     -command => \&select_source)->pack(-side => 'left', -padx => 3);

$top->Label(-text => 'Frames:')->pack(-side => 'left', -padx => 6);
$top->Entry(-textvariable => \$frames, -width => 6)->pack(-side => 'left');

$top->Checkbutton(-text => 'Fairings', -variable => \$fairing_on)->pack(-side => 'left', -padx => 8);
$top->Checkbutton(-text => 'Front', -variable => \$fairing_front)->pack(-side => 'left', -padx => 2);
$top->Checkbutton(-text => 'Back',  -variable => \$fairing_back)->pack(-side => 'left', -padx => 2);

$top->Label(-text => 'Fairing:')->pack(-side => 'left', -padx => 4);
$top->Optionmenu(
    -options => [qw(linear cosine smoothstep)],
    -textvariable => \$fairing_style,
)->pack(-side => 'left');

$top->Button(-text => 'Show', -command => sub { $show_composite = 1; update_scaled_preview(); redraw(); })->pack(-side => 'left', -padx => 12);
$top->Button(-text => 'Make Scaled Images', -command => \&make_scaled)->pack(-side => 'left', -padx => 3);

my $status = $mw->Label(-text => 'Ready — select background and overlay CSVs', -anchor => 'w', -relief => 'sunken')
    ->pack(-side => 'bottom', -fill => 'x');

my $canvas = $mw->Canvas(-width => 1280, -height => 720, -background => '#1a2028', -highlightthickness => 0)
    ->pack(-side => 'top', -fill => 'both', -expand => 1, -padx => 6, -pady => 4);

$canvas->CanvasBind('<Button-1>' => \&on_press);
$canvas->CanvasBind('<B1-Motion>' => \&on_motion);
$canvas->CanvasBind('<ButtonRelease-1>' => sub { undef $resize_drag; });

sub set_status { $status->configure(-text => $_[0]); }

sub select_bg {
    my $file = $mw->getOpenFile(-filetypes => [['CSV', '.csv'], ['All', '*']], -title => 'Background CSV');
    return unless $file;
    $bg_csv = $file;
    $bg_image_path = first_image_from_csv($file);
    $bg_item = undef;
    if ($bg_image_path && -f $bg_image_path) {
        eval {
            my $p = $mw->Photo(-file => $bg_image_path);
            my $w = $p->width;
            my $h = $p->height;
            $canvas->configure(-width => $w, -height => $h);
        };
    }
    set_status("Background: " . basename($file));
    redraw();
}

sub select_overlay {
    my $file = $mw->getOpenFile(-filetypes => [['CSV', '.csv'], ['All', '*']], -title => 'Overlay CSV');
    return unless $file;
    $overlay_csv = $file;
    $overlay_image_path = first_image_from_csv($file);
    if ($overlay_image_path && -f $overlay_image_path) {
        eval {
            my $p = $mw->Photo(-file => $overlay_image_path);
            my $w = $p->width;
            my $h = $p->height;
            $resize_aspect = $h ? $w / $h : 1;
            $rect{start_w} = $w;
            $rect{start_h} = $h;
            $rect{end_w}   = int($w * 1.6);
            $rect{end_h}   = int($h * 1.6);
        };
    }
    set_status("Overlay: " . basename($file));
    $show_composite = 0;
    redraw();
}

sub select_source {
    my $dir = $mw->chooseDirectory(-title => 'Source directory (large images)');
    return unless defined $dir && -d $dir;
    $source_dir = $dir;
    set_status("Source dir: $dir");
}

sub first_image_from_csv {
    my ($csv) = @_;
    open my $fh, '<', $csv or return;
    while (my $line = <$fh>) {
        next unless $line =~ /\S/;
        my $rec = parse_placement_line($line);
        if ($rec && $rec->{image}) {
            close $fh;
            return find_image_path($rec->{image}, dirname($csv));
        }
    }
    close $fh;
    return;
}

sub parse_placement_line {
    my ($line) = @_;
    chomp $line;
    $line =~ s/\r\z//;
    return unless $line =~ /\S/;
    my @f = split /,/, $line, -1;
    my %rec;
    if (@f >= 6) {
        for (my $i = 0; $i + 1 < @f; $i += 2) {
            $rec{$f[$i]} = $f[$i + 1] if defined $f[$i] && $f[$i] ne '';
        }
    } elsif (@f >= 3) {
        @rec{qw(image x y)} = @f[0..2];
    }
    return unless $rec{image};
    $rec{x} //= 0;
    $rec{y} //= 0;
    return \%rec;
}

sub find_image_path {
    my ($image, $clip_dir) = @_;
    return unless defined $image && $image ne '';
    return $image if File::Spec->file_name_is_absolute($image) && -f $image;
    my @try = (
        File::Spec->catfile($project_root, $image),
        File::Spec->catfile($clip_dir, $image),
        File::Spec->catfile(dirname($clip_dir), $image),
    );
    for my $p (@try) {
        return abs_path($p) if -f $p;
    }
    return;
}

# Extract a useful number from a filename and find the matching large image
# in the source directory (ignores extra suffixes like _100).
sub find_big_image {
    my ($small_name, $source_dir) = @_;
    return unless $source_dir && -d $source_dir && $small_name;

    my $base = basename($small_name);
    $base =~ s/\.\w+$//;

    my @nums = $base =~ /(\d+)/g;
    return unless @nums;

    # Prefer the first substantial number; skip a trailing size-like number
    my $key = $nums[-1];
    if (@nums > 1 && $nums[-1] =~ /^(100|50|25|200|400|150)$/) {
        $key = $nums[-2];
    }

    opendir my $dh, $source_dir or return;
    my @candidates;
    while (my $f = readdir $dh) {
        next unless $f =~ /\.(png|jpg|jpeg|tif|tiff)$/i;
        next if $f eq basename($small_name);
        if ($f =~ /$key/) {
            push @candidates, File::Spec->catfile($source_dir, $f);
        }
    }
    closedir $dh;

    @candidates = sort { length($a) <=> length($b) } @candidates;
    return $candidates[0] if @candidates;
    return;
}

sub redraw {
    # Background only created once
    unless ($bg_item) {
        my $cw = $canvas->cget('-width');
        my $ch = $canvas->cget('-height');
        $canvas->createRectangle(0, 0, $cw, $ch, -fill => '#1a2028', -outline => '#1a2028', -tags => 'bg_fill');
        if ($bg_image_path && -f $bg_image_path) {
            my $photo = get_photo($bg_image_path);
            $bg_item = $canvas->createImage(0, 0, -anchor => 'nw', -image => $photo, -tags => 'background') if $photo;
        }
    }

    # Small overlay at start
    $canvas->delete('start_image');
    if ($overlay_image_path && -f $overlay_image_path) {
        my $photo = get_photo($overlay_image_path);
        if ($photo) {
            $start_img_item = $canvas->createImage($rect{start_x}, $rect{start_y}, -anchor => 'nw', -image => $photo, -tags => 'start_image');
        }
    }

    # Scaled preview at end (only if Show is on and we have a cached photo)
    $canvas->delete('end_image');
    if ($show_composite && $scaled_photo) {
        $end_img_item = $canvas->createImage($rect{end_x}, $rect{end_y}, -anchor => 'nw', -image => $scaled_photo, -tags => 'end_image');
    }

    draw_rects();
}

sub update_scaled_preview {
    return unless $show_composite && $source_dir && $overlay_image_path;
    my $big_path = find_big_image($overlay_image_path, $source_dir);
    return unless $big_path && -f $big_path;
    my $tmp = '/tmp/overlay_preview.png';
    eval {
        my $img = Image::Imlib2->load($big_path);
        my $scaled = $img->create_scaled_image($rect{end_w}, $rect{end_h});
        $scaled->save($tmp);
        $scaled_photo = $mw->Photo(-file => $tmp);
    };
    set_status("Showing large image: " . basename($big_path)) if $scaled_photo;
}

sub draw_rects {
    $canvas->delete('rect_start');
    $canvas->delete('rect_end');
    my @s = ($rect{start_x}, $rect{start_y},
             $rect{start_x} + $rect{start_w}, $rect{start_y} + $rect{start_h});
    my @e = ($rect{end_x}, $rect{end_y},
             $rect{end_x} + $rect{end_w}, $rect{end_y} + $rect{end_h});
    $start_rect_item = $canvas->createRectangle(@s, -outline => 'red',   -width => 3, -tags => 'rect_start');
    $end_rect_item   = $canvas->createRectangle(@e, -outline => 'cyan',  -width => 3, -tags => 'rect_end');
}

sub get_photo {
    my ($path) = @_;
    return $photo_cache{$path} if $photo_cache{$path};
    my $photo;
    eval { $photo = $mw->Photo(-file => $path); 1 } or return;
    $photo_cache{$path} = $photo;
    return $photo;
}

sub on_press {
    my $x = $canvas->canvasx($Tk::event->x);
    my $y = $canvas->canvasy($Tk::event->y);
    my @hit = hit_rect($x, $y);
    if (@hit) {
        my ($which, $mode, $corner) = @hit;
        $resize_drag = {
            which  => $which,
            mode   => $mode,
            corner => $corner,
            ox     => $x,
            oy     => $y,
            orig_x => $rect{"${which}_x"},
            orig_y => $rect{"${which}_y"},
            orig_w => $rect{"${which}_w"},
            orig_h => $rect{"${which}_h"},
        };
    }
}

sub on_motion {
    return unless $resize_drag;
    my $x = $canvas->canvasx($Tk::event->x);
    my $y = $canvas->canvasy($Tk::event->y);
    my $dx = $x - $resize_drag->{ox};
    my $dy = $y - $resize_drag->{oy};
    my $which = $resize_drag->{which};

    if ($resize_drag->{mode} eq 'move') {
        my $new_x = int($resize_drag->{orig_x} + $dx);
        my $new_y = int($resize_drag->{orig_y} + $dy);
        my $move_dx = $new_x - $rect{"${which}_x"};
        my $move_dy = $new_y - $rect{"${which}_y"};
        $rect{"${which}_x"} = $new_x;
        $rect{"${which}_y"} = $new_y;

        if ($which eq 'start') {
            $canvas->move('start_image', $move_dx, $move_dy) if $start_img_item;
            $canvas->move('rect_start', $move_dx, $move_dy);
        } else {
            $canvas->move('end_image', $move_dx, $move_dy) if $end_img_item;
            $canvas->move('rect_end', $move_dx, $move_dy);
        }
    } else {
        my $corner = $resize_drag->{corner};
        my $nw = $resize_drag->{orig_w};
        my $nh = $resize_drag->{orig_h};
        my $nx = $resize_drag->{orig_x};
        my $ny = $resize_drag->{orig_y};

        if ($corner eq 'br') {
            $nw = $resize_drag->{orig_w} + $dx;
            $nh = $nw / $resize_aspect;
        } elsif ($corner eq 'bl') {
            $nw = $resize_drag->{orig_w} - $dx;
            $nh = $nw / $resize_aspect;
            $nx = $resize_drag->{orig_x} + $dx;
        } elsif ($corner eq 'tr') {
            $nw = $resize_drag->{orig_w} + $dx;
            $nh = $nw / $resize_aspect;
            $ny = $resize_drag->{orig_y} + ($resize_drag->{orig_h} - $nh);
        } elsif ($corner eq 'tl') {
            $nw = $resize_drag->{orig_w} - $dx;
            $nh = $nw / $resize_aspect;
            $nx = $resize_drag->{orig_x} + $dx;
            $ny = $resize_drag->{orig_y} + ($resize_drag->{orig_h} - $nh);
        }
        $nw = 16 if $nw < 16;
        $nh = 16 if $nh < 16;
        $rect{"${which}_w"} = int($nw);
        $rect{"${which}_h"} = int($nh);
        $rect{"${which}_x"} = int($nx);
        $rect{"${which}_y"} = int($ny);
    }
    # Update only the moved items — do not rebuild the background
    if ($resize_drag->{mode} ne 'move') {
        # Resize: just redraw the two rectangles and the images (background stays)
        $canvas->delete('start_image');
        $canvas->delete('end_image');
        $canvas->delete('rect_start');
        $canvas->delete('rect_end');
        if ($overlay_image_path && -f $overlay_image_path) {
            my $photo = get_photo($overlay_image_path);
            $start_img_item = $canvas->createImage($rect{start_x}, $rect{start_y}, -anchor => 'nw', -image => $photo, -tags => 'start_image') if $photo;
        }
        if ($show_composite && $scaled_photo) {
            # Re-scale only on resize (not on pure move)
            update_scaled_preview();
            $end_img_item = $canvas->createImage($rect{end_x}, $rect{end_y}, -anchor => 'nw', -image => $scaled_photo, -tags => 'end_image') if $scaled_photo;
        }
        draw_rects();
    }
}

sub hit_rect {
    my ($x, $y) = @_;
    my $tol = 14;
    for my $which (qw(end start)) {
        my $x1 = $rect{"${which}_x"};
        my $y1 = $rect{"${which}_y"};
        my $x2 = $x1 + $rect{"${which}_w"};
        my $y2 = $y1 + $rect{"${which}_h"};
        for my $c ([$x1, $y1, 'tl'], [$x2, $y1, 'tr'], [$x1, $y2, 'bl'], [$x2, $y2, 'br']) {
            if (abs($x - $c->[0]) <= $tol && abs($y - $c->[1]) <= $tol) {
                return ($which, 'resize', $c->[2]);
            }
        }
        if ($x >= $x1 && $x <= $x2 && $y >= $y1 && $y <= $y2) {
            return ($which, 'move');
        }
    }
    return;
}

sub fairing {
    my ($t, $style) = @_;
    $t = 0 if $t < 0;
    $t = 1 if $t > 1;
    $style = lc($style || 'linear');
    return (1 - cos($t * 3.14159265358979)) / 2 if $style eq 'cosine';
    return $t * $t * (3 - 2 * $t) if $style eq 'smoothstep';
    return $t;
}

sub make_scaled {
    return unless $overlay_csv && $source_dir;
    unless (defined $save_dir && -d $save_dir) {
        $save_dir = $mw->chooseDirectory(-title => 'Save scaled images to');
        return unless defined $save_dir && $save_dir ne '';
    }
    make_path($save_dir) unless -d $save_dir;

    open my $fh, '<', $overlay_csv or do { set_status("Cannot read overlay CSV"); return; };
    my @lines;
    while (<$fh>) { chomp; push @lines, $_ if /\S/; }
    close $fh;
    return unless @lines;

    my $count = $frames > 0 ? $frames : scalar @lines;
    $count = @lines if $count > @lines;

    my $out_csv = File::Spec->catfile($save_dir, 'scaled.csv');
    open my $out, '>', $out_csv or do { set_status("Cannot write CSV"); return; };

    my $written = 0;
    for my $i (0 .. $count - 1) {
        my $rec = parse_placement_line($lines[$i]);
        next unless $rec && $rec->{image};

        my $prog = $count > 1 ? $i / ($count - 1) : 0;
        if ($fairing_on) {
            if ($fairing_front && !$fairing_back) {
                # front only: start slow, accelerate (ease-in)
                $prog = $prog * $prog;
            } elsif ($fairing_back && !$fairing_front) {
                # back only: start fast, decelerate (ease-out)
                $prog = 1 - (1 - $prog) * (1 - $prog);
            } elsif ($fairing_front && $fairing_back) {
                # both: classic ease-in-out
                $prog = fairing($prog, $fairing_style);
            }
        }

        my $w = int($rect{start_w} + ($rect{end_w} - $rect{start_w}) * $prog);
        my $h = int($rect{start_h} + ($rect{end_h} - $rect{start_h}) * $prog);
        my $x = int($rect{start_x} + ($rect{end_x} - $rect{start_x}) * $prog);
        my $y = int($rect{start_y} + ($rect{end_y} - $rect{start_y}) * $prog);

        my $src = find_big_image($rec->{image}, $source_dir);
        next unless $src && -f $src;

        my $dest = File::Spec->catfile($save_dir, sprintf("scaled_%04d.png", $i + 1));

        eval {
            my $img = Image::Imlib2->load($src);
            my $scaled = $img->create_scaled_image($w, $h);
            $scaled->save($dest);
            $written++;
        };

        print $out join(',',
            'image', basename($dest),
            'w', $w, 'h', $h, 'x', $x, 'y', $y
        ), "\n";
    }
    close $out;
    set_status("Wrote $written scaled frames to $save_dir");
}

MainLoop;
