#!/usr/bin/env perl
# csv_shift_by_drag.pl
# Load a CSV of centre-relative positions, show one frame on a canvas,
# drag it to the desired place on the new background, then apply the
# same delta to every line in the CSV.
#
# CSV format expected (same as the rest of your tools):
#   type,path/to/image.png,w,100,h,100,x,781,y,404
#
# Requires: Perl + Tk + Tk::PNG + Tk::JPEG + Text::CSV

use strict;
use warnings;
use Tk;
use Tk::PNG;
use Tk::JPEG;
use File::Basename qw(basename dirname);
use File::Spec;
use Cwd qw(abs_path);
use Text::CSV;

# ---------- helpers ----------
sub trim {
    my $s = shift // '';
    $s =~ s/^\s+|\s+$//g;
    return $s;
}

sub parse_num {
    my $s = trim(shift // '');
    return undef unless $s =~ /^-?\d+(?:\.\d+)?$/;
    return 0 + $s;
}

sub format_num {
    my $n = shift;
    return int($n + ($n < 0 ? -0.5 : 0.5));   # round to nearest integer
}

sub line_to_hash {
    my ($csv, $line) = @_;
    return undef if !defined $line || $line =~ /^\s*$/;
    chomp $line;
    my $ok = $csv->parse($line);
    my @fields = $ok ? $csv->fields : split /,/, $line;
    my %h;
    if (@fields >= 2) {
        $h{_type} = trim($fields[0]);
        $h{_path} = trim($fields[1]);
    }
    for (my $i = 2; $i < @fields - 1; $i += 2) {
        my $lab = lc trim($fields[$i]);
        my $val = trim($fields[$i+1]);
        $h{$lab} = $val if $lab ne '';
    }
    return \%h;
}

sub hash_to_line {
    my ($csv, $h) = @_;
    my @out;
    push @out, $h->{_type} if exists $h->{_type};
    push @out, $h->{_path} if exists $h->{_path};
    for my $k (qw(w h x y)) {
        push @out, $k, $h->{$k} if exists $h->{$k};
    }
    for my $k (sort keys %$h) {
        next if $k =~ /^_/ || $k =~ /^(w|h|x|y)$/;
        push @out, $k, $h->{$k};
    }
    return $csv->combine(@out) ? $csv->string : join(',', @out);
}

# ---------- state ----------
my $csv_obj = Text::CSV->new({ binary => 1, auto_diag => 0 });
my @records;          # array of hashrefs
my $csv_path = '';
my $image_dir = '.';
my $current_index = 0;
my $canvas_w = 1920;
my $canvas_h = 1080;
my $bg_path = '';
my $overlay_photo;
my $bg_photo;
my $drag_start_x;
my $drag_start_y;
my $item_id;
my $status_text = 'Load a CSV to begin';

# ---------- GUI ----------
my $mw = MainWindow->new;
$mw->title('CSV Shift by Drag');
#$mw->geometry('1400x900');
$mw->geometry('1400x1000');
$mw->optionAdd('*font', ['Helvetica', 14]);
$mw->optionAdd('*Dialog*font', ['Helvetica', 14]);
$mw->optionAdd('*FileSelect*font', ['Helvetica', 14]);
$mw->optionAdd('*Listbox*font', ['Helvetica', 14]);
$mw->optionAdd('*Entry*font', ['Helvetica', 14]);
my $top = $mw->Frame->pack(-fill => 'x', -padx => 8, -pady => 6);

$top->Button(-text => 'Load CSV', -command => \&load_csv)->pack(-side => 'left', -padx => 4);
$top->Button(-text => 'Load Background', -command => \&load_background)->pack(-side => 'left', -padx => 4);

$top->Label(-text => 'Canvas W:')->pack(-side => 'left', -padx => 4);
my $e_cw = $top->Entry(-width => 7)->pack(-side => 'left');
$e_cw->insert(0, $canvas_w);
$top->Label(-text => 'H:')->pack(-side => 'left');
my $e_ch = $top->Entry(-width => 7)->pack(-side => 'left', -padx => 2);
$e_ch->insert(0, $canvas_h);

$top->Button(-text => 'Apply size', -command => \&apply_canvas_size)->pack(-side => 'left', -padx => 6);

$top->Label(-text => 'Frame:')->pack(-side => 'left', -padx => 8);
my $e_frame = $top->Entry(-textvariable => \$current_index, -width => 6)->pack(-side => 'left');
$top->Button(-text => 'Show', -command => \&show_current)->pack(-side => 'left', -padx => 4);

$top->Button(-text => 'This is the new position', -command => \&apply_shift,
             -background => '#ffe680')->pack(-side => 'left', -padx => 12);

my $canvas_frame = $mw->Frame->pack(-fill => 'both', -expand => 1, -padx => 8, -pady => 4);
my $xscroll = $canvas_frame->Scrollbar(-orient => 'horizontal');
my $yscroll = $canvas_frame->Scrollbar(-orient => 'vertical');
my $canvas = $canvas_frame->Canvas(
    -width => 1200,
    -height => 700,
    -background => '#222',
    -highlightthickness => 1,
    -xscrollcommand => ['set', $xscroll],
    -yscrollcommand => ['set', $yscroll],
    -scrollregion => [0, 0, $canvas_w, $canvas_h]
);
$xscroll->configure(-command => ['xview', $canvas]);
$yscroll->configure(-command => ['yview', $canvas]);
$yscroll->pack(-side => 'right', -fill => 'y');
$xscroll->pack(-side => 'bottom', -fill => 'x');
$canvas->pack(-side => 'left', -fill => 'both', -expand => 1);

my $status = $mw->Label(-textvariable => \$status_text, -anchor => 'w', -relief => 'sunken')
                ->pack(-fill => 'x', -padx => 8, -pady => 4);

# ---------- actions ----------
sub safe_int {
    my $v = shift;
    return 0 unless defined $v && $v =~ /^-?\d+(?:\.\d+)?$/;
    return int($v + 0);
}

sub apply_canvas_size {
    my $w = safe_int($e_cw->get) || safe_int($canvas_w) || 1920;
    my $h = safe_int($e_ch->get) || safe_int($canvas_h) || 1080;
    $canvas_w = $w;
    $canvas_h = $h;
    $canvas->configure(-scrollregion => [0, 0, $canvas_w, $canvas_h]);
    redraw();
}

sub load_background {
    my $path = $mw->getOpenFile(-title => 'Select background image',
                                -filetypes => [['Images', ['.png', '.jpg', '.jpeg']], ['All', '*']]);
    return unless $path && -f $path;
    $bg_path = $path;
    my $photo;
    eval { $photo = $mw->Photo(-file => $path); };
    if (!$photo || $@) {
        $status_text = "Failed to load background: $@";
        return;
    }
    $bg_photo = $photo;
    my $w = safe_int($bg_photo->width)  || 1920;
    my $h = safe_int($bg_photo->height) || 1080;
    $canvas_w = $w;
    $canvas_h = $h;
    # update entries without relying on textvariable side-effects
    $e_cw->delete(0, 'end');
    $e_cw->insert('end', $canvas_w);
    $e_ch->delete(0, 'end');
    $e_ch->insert('end', $canvas_h);
    $canvas->configure(-scrollregion => [0, 0, $canvas_w, $canvas_h]);
    $status_text = "Background: " . basename($path) . "  (${canvas_w}x${canvas_h})";
    redraw();
}

sub load_csv {
    my $path = $mw->getOpenFile(-title => 'Select CSV', -filetypes => [['CSV', '.csv'], ['All', '*']]);
    return unless $path;
    $csv_path = $path;
    $image_dir = dirname($path);
    @records = ();
    open my $fh, '<', $path or do {
        $status_text = "Cannot open $path";
        return;
    };
    while (my $line = <$fh>) {
        my $h = line_to_hash($csv_obj, $line);
        push @records, $h if $h && defined $h->{x} && defined $h->{y};
    }
    close $fh;
    $current_index = 0;
    $status_text = "Loaded " . scalar(@records) . " records from " . basename($path);
    show_current();
}

sub show_current {
    return unless @records;
    $current_index = 0 if $current_index < 0;
    $current_index = $#records if $current_index > $#records;
    redraw();
    my $r = $records[$current_index];
    $status_text = sprintf("Frame %d / %d   x=%s y=%s   %s",
                           $current_index + 1, scalar(@records),
                           $r->{x}, $r->{y}, basename($r->{_path} // ''));
}

sub redraw {
    $canvas->delete('all');
    # background
    if ($bg_photo) {
        $canvas->createImage(0, 0, -anchor => 'nw', -image => $bg_photo, -tags => 'bg');
    } else {
        my $w = safe_int($canvas_w) || 1920;
        my $h = safe_int($canvas_h) || 1080;
        $canvas->createRectangle(0, 0, $w, $h, -fill => '#333', -outline => '#333');
    }
    # overlay
    return unless @records && $records[$current_index];
    my $r = $records[$current_index];
    my $img_path = $r->{_path} // '';
    unless (File::Spec->file_name_is_absolute($img_path)) {
        $img_path = File::Spec->catfile($image_dir, $img_path);
    }
    unless (-f $img_path) {
        $status_text = "Cannot find image: $img_path";
        return;
    }
    eval { $overlay_photo = $mw->Photo(-file => $img_path); };
    unless ($overlay_photo) {
        $status_text = "Failed to load image: $img_path";
        return;
    }

    my $iw = $overlay_photo->width || 0;
    my $ih = $overlay_photo->height || 0;
    my $cx = parse_num($r->{x}) // 0;
    my $cy = parse_num($r->{y}) // 0;
    my $cw = safe_int($canvas_w) || 1920;
    my $ch = safe_int($canvas_h) || 1080;

    # Show centred on the canvas so it's easy to find and drag
    my $tl_x = int(($cw - $iw) / 2);
    my $tl_y = int(($ch - $ih) / 2);

    $item_id = $canvas->createImage($tl_x, $tl_y, -anchor => 'nw', -image => $overlay_photo, -tags => 'overlay');
    $canvas->bind('overlay', '<ButtonPress-1>' => \&start_drag);
    $canvas->bind('overlay', '<B1-Motion>'     => \&do_drag);

    $status_text = sprintf("Frame %d  %dx%d  (CSV centre %s,%s)  shown centred for positioning",
                           $current_index + 1, $iw, $ih, $cx, $cy);
}

sub start_drag {
    my $e = $Tk::event;
    $drag_start_x = $canvas->canvasx($e->x);
    $drag_start_y = $canvas->canvasy($e->y);
}

sub do_drag {
    my $e = $Tk::event;
    my $x = $canvas->canvasx($e->x);
    my $y = $canvas->canvasy($e->y);
    my $dx = $x - $drag_start_x;
    my $dy = $y - $drag_start_y;
    $canvas->move('overlay', $dx, $dy);
    $drag_start_x = $x;
    $drag_start_y = $y;
}

sub apply_shift {
    return unless @records && $item_id;
    my $r = $records[$current_index];
    my $old_cx = parse_num($r->{x}) // 0;
    my $old_cy = parse_num($r->{y}) // 0;

    # current top-left of the dragged image
    my ($tl_x, $tl_y) = $canvas->coords($item_id);
    my $iw = $overlay_photo->width;
    my $ih = $overlay_photo->height;
    # convert back to centre-relative on this canvas
    my $new_cx = $tl_x - ($canvas_w - $iw) / 2;
    my $new_cy = $tl_y - ($canvas_h - $ih) / 2;

    my $delta_x = $new_cx - $old_cx;
    my $delta_y = $new_cy - $old_cy;

    my $msg = sprintf("Apply delta  x=%+.2f  y=%+.2f\nto all %d records?", $delta_x, $delta_y, scalar(@records));
    my $ans = $mw->messageBox(-title => 'Confirm shift', -message => $msg, -type => 'yesno', -icon => 'question');
    return unless $ans eq 'Yes';

    for my $rec (@records) {
        my $x = parse_num($rec->{x}) // 0;
        my $y = parse_num($rec->{y}) // 0;
        $rec->{x} = format_num($x + $delta_x);
        $rec->{y} = format_num($y + $delta_y);
    }

    # write new file
    my $out_path = $csv_path;
    $out_path =~ s/\.csv$/_shifted.csv/i;
    $out_path .= '_shifted.csv' if $out_path eq $csv_path;
    open my $out, '>', $out_path or do {
        $status_text = "Cannot write $out_path";
        return;
    };
    for my $rec (@records) {
        print $out hash_to_line($csv_obj, $rec), "\n";
    }
    close $out;
    $status_text = "Wrote " . basename($out_path) . "  (delta x=$delta_x y=$delta_y)";
    $mw->messageBox(-title => 'Done', -message => "Saved:\n$out_path", -type => 'ok');
}

$mw->bind('<Left>'  => sub { $current_index--; show_current(); });
$mw->bind('<Right>' => sub { $current_index++; show_current(); });

MainLoop;
