#!/usr/bin/perl
use strict;
use warnings;
use Tk;
use File::Spec;
use File::Basename;

# --- Minimal Catmull-Rom ---
{
    package My::CatmullRom;
    sub new {
        my ($class, $points) = @_;
        die "Need at least 4 control points" unless @$points >= 4;
        bless { points => $points }, $class;
    }
    sub evaluate {
        my ($self, $t) = @_;
        my $p = $self->{points};
        my $n = @$p - 1;
        return $p->[0] if $t <= 0;
        return $p->[$n] if $t >= $n;
        my $i = int($t);
        my $frac = $t - $i;
        my $p0 = $p->[ $i > 0      ? $i - 1 : 0 ];
        my $p1 = $p->[ $i ];
        my $p2 = $p->[ $i + 1 <= $n ? $i + 1 : $n ];
        my $p3 = $p->[ $i + 2 <= $n ? $i + 2 : $n ];
        my $t2 = $frac * $frac;
        my $t3 = $t2 * $frac;
        return 0.5 * (
            2 * $p1 +
            (-$p0 + $p2) * $frac +
            (2*$p0 - 5*$p1 + 4*$p2 - $p3) * $t2 +
            (-$p0 + 3*$p1 - 3*$p2 + $p3) * $t3
        );
    }
}

# --- Globals for navigator ---
my @dir_stack = ('.');
my $selected_file = '';
my $selected_dir  = '.';

# --- Main Window ---
my $mw = MainWindow->new;
$mw->title("CSV Spline Interpolator");
$mw->geometry("1100x1000+200+100");

my $font = ['Arial', 16];

# Top label
$mw->Label(-text => "Directory Navigator (double-click dirs to enter, files to select)\n Makes curved inbetweens of x,y values in csv file lines", 
           -font => $font)->pack(-pady => 5);

# Navigation frame (grid so we can put GO UP directly under the listbox)
my $nav_frame = $mw->Frame->pack(-fill => 'both', -expand => 1, -padx => 10);

# Listbox (row 0, column 0)
my $listbox = $nav_frame->Scrolled('Listbox', 
    -font => $font, 
    -scrollbars => 'se', 
    -width => 30, 
    -height => 15
)->grid(-row => 0, -column => 0, -sticky => 'nsew');

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

# GO UP button directly under the listbox (row 1, column 0)
$nav_frame->Button(
    -text => 'GO UP',
    -font => $font,
    -width => 12,
    -command => \&GO_UP
)->grid(-row => 1, -column => 0, -sticky => 'w', -pady => 5);

# Message box (spans both rows so bottom lines up with the GO UP button)
my $message_box = $nav_frame->Scrolled('Listbox', 
    -font => $font, 
    -scrollbars => 'se', 
    -width => 40, 
    -height => 5
)->grid(-row => 0, -column => 1, -rowspan => 1, -sticky => 'nsew', -padx => 10);

# Let the listbox and message box expand properly
$nav_frame->gridColumnconfigure(0, -weight => 1);
$nav_frame->gridColumnconfigure(1, -weight => 1);
$nav_frame->gridRowconfigure(0, -weight => 1);

# Controls frame
my $ctrl_frame = $mw->Frame->pack(-fill => 'x', -padx => 10, -pady => 10);

$ctrl_frame->Label(-text => "Selected directory:", -font => $font)->grid(-row => 0, -column => 0, -sticky => 'w');
my $dir_entry = $ctrl_frame->Entry(-textvariable => \$selected_dir, -font => $font, -width => 40)
    ->grid(-row => 0, -column => 1, -sticky => 'w', -padx => 5);

$ctrl_frame->Label(-text => "Selected file:", -font => $font)->grid(-row => 1, -column => 0, -sticky => 'w', -pady => 3);
my $file_entry = $ctrl_frame->Entry(-textvariable => \$selected_file, -font => $font, -width => 40)
    ->grid(-row => 1, -column => 1, -sticky => 'w', -padx => 5);

my $steps = 1;
$ctrl_frame->Label(-text => "In-between steps:", -font => $font)->grid(-row => 2, -column => 0, -sticky => 'w', -pady => 5);
my $steps_entry = $ctrl_frame->Entry(-textvariable => \$steps, -font => $font, -width => 10)
    ->grid(-row => 2, -column => 1, -sticky => 'w', -padx => 5);

my $outfile = "output.csv";
$ctrl_frame->Label(-text => "Output filename:", -font => $font)->grid(-row => 3, -column => 0, -sticky => 'w');
my $outfile_entry = $ctrl_frame->Entry(-textvariable => \$outfile, -font => $font, -width => 30)
    ->grid(-row => 3, -column => 1, -sticky => 'w', -padx => 5);

my $status = $mw->Label(-text => "Select file or directory, set steps, then Apply", 
                        -font => $font)->pack(-pady => 5);

# Bottom buttons
my $btn_frame = $mw->Frame->pack(-side => 'bottom', -fill => 'x', -pady => 10);
$btn_frame->Button(
    -text    => "Apply to file",
    -font    => $font,
    -width   => 16,
    -command => \&do_apply_file
)->pack(-side => 'left', -padx => 10);

$btn_frame->Button(
    -text    => "Apply to directory",
    -font    => $font,
    -width   => 18,
    -command => \&do_apply_directory
)->pack(-side => 'left', -padx => 10);

$btn_frame->Button(
    -text    => "Quit",
    -font    => $font,
    -width   => 12,
    -command => sub { $mw->destroy }
)->pack(-side => 'right', -padx => 20);

# Initial population
refresh_listbox();

MainLoop;

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

    opendir(my $dh, $dir) or do {
        $message_box->insert('end', "Can't open $dir: $!");
        return;
    };
    my @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 =~ /\.(csv|list)$/i) {
            $listbox->insert('end', $item);
        }
    }
}

sub select_item {
    my $selection = $listbox->get('active');
    return unless defined $selection && $selection ne '';

    my $path = File::Spec->catfile($dir_stack[-1], $selection);

    if (-d $path) {
        push @dir_stack, $path;
        refresh_listbox();
        $selected_dir = $path;
        $message_box->delete(0, 'end');
        $message_box->insert('end', "Selected directory: $selected_dir");
    } elsif (-f $path) {
        $selected_file = $path;
        $selected_dir  = $dir_stack[-1];   # keep dir in sync
        $message_box->delete(0, 'end');
        $message_box->insert('end', "Selected file: $selected_file");
    }
    # refresh not always needed after file select, but harmless
    refresh_listbox() if -d $path;
}

sub GO_UP {
    pop @dir_stack if @dir_stack > 1;
    refresh_listbox();
    $selected_dir = $dir_stack[-1];
    $message_box->delete(0, 'end');
    $message_box->insert('end', "Now in: $selected_dir");
}

sub do_apply_file {
    unless (defined $selected_file && $selected_file ne '' && -f $selected_file) {
        $message_box->delete(0, 'end');
        $message_box->insert('end', "Please select a file first.");
        return;
    }
    unless ($steps =~ /^\d+$/ && $steps > 0) {
        $message_box->delete(0, 'end');
        $message_box->insert('end', "Steps must be a positive integer.");
        return;
    }
    unless ($outfile =~ /\S/) {
        $message_box->delete(0, 'end');
        $message_box->insert('end', "Output filename is empty.");
        return;
    }

    $message_box->delete(0, 'end');
    $message_box->insert('end', "Processing file: $selected_file ...");
    $mw->update;

    my $res = eval { run_interpolation($selected_file, $steps, $outfile) };
    if ($@) {
        $message_box->delete(0, 'end');
        $message_box->insert('end', "Error: $@");
    } else {
        $message_box->delete(0, 'end');
        $message_box->insert('end', "Done. Output: $outfile");
    }
}

sub do_apply_directory {
    my $dir = $selected_dir;
    $dir = $dir_stack[-1] unless defined $dir && $dir ne '' && -d $dir;

    unless (-d $dir) {
        $message_box->delete(0, 'end');
        $message_box->insert('end', "No valid directory selected.");
        return;
    }
    unless ($steps =~ /^\d+$/ && $steps > 0) {
        $message_box->delete(0, 'end');
        $message_box->insert('end', "Steps must be a positive integer.");
        return;
    }

    opendir(my $dh, $dir) or do {
        $message_box->delete(0, 'end');
        $message_box->insert('end', "Can't open directory $dir: $!");
        return;
    };
    my @csvs = grep { /\.csv$/i && -f File::Spec->catfile($dir, $_) } readdir($dh);
    closedir($dh);
    @csvs = sort { lc($a) cmp lc($b) } @csvs;

    if (!@csvs) {
        $message_box->delete(0, 'end');
        $message_box->insert('end', "No .csv files found in $dir");
        return;
    }

    # Create output directory: <basename of selected dir>_splined in current directory
    my $base = basename($dir);
    $base = 'root' if $base eq '' || $base eq '.' || $base eq '/';
    my $outdir = $base . "_splined";
    if (!-d $outdir) {
        mkdir $outdir or do {
            $message_box->delete(0, 'end');
            $message_box->insert('end', "Can't create directory $outdir: $!");
            return;
        };
    }

    $message_box->delete(0, 'end');
    $message_box->insert('end', "Processing " . scalar(@csvs) . " .csv file(s) into $outdir ...");
    $mw->update;

    my $ok = 0;
    my $fail = 0;
    for my $name (@csvs) {
        my $inpath = File::Spec->catfile($dir, $name);
        my ($base_name, $path, $suffix) = fileparse($name, qr/\.[^.]*$/);
        my $outname = $base_name . "_splined.csv";
        my $outpath = File::Spec->catfile($outdir, $outname);

        $message_box->insert('end', "  $name -> $outdir/$outname");
        $mw->update;

        my $res = eval { run_interpolation($inpath, $steps, $outpath) };
        if ($@) {
            $message_box->insert('end', "    Error: $@");
            $fail++;
        } else {
            $ok++;
        }
    }

    $message_box->insert('end', "Finished. Success: $ok  Failed: $fail  (in $outdir)");
}

# --- Interpolation Logic ---
sub run_interpolation {
    my ($file, $steps, $outfile) = @_;

    open my $in, '<', $file or die "Can't open $file: $!";

    my (@x, @y, @lines);
    while (<$in>) {
        chomp;
        next unless /\S/;
        my @fields = split /,/;
        my %rec;
        for (my $i = 0; $i < @fields; $i += 2) {
            $rec{ $fields[$i] } = $fields[$i + 1] if defined $fields[$i + 1];
        }
        if (defined $rec{'x'} && defined $rec{'y'}) {
            push @x, $rec{'x'} + 0;   # numeric
            push @y, $rec{'y'} + 0;
            push @lines, { %rec };
        }
    }
    close $in;

    die "Need at least 4 coordinate pairs for interpolation." unless @x >= 4;

    my $spline_x = My::CatmullRom->new(\@x);
    my $spline_y = My::CatmullRom->new(\@y);
    my @t = (0 .. $#x);

    open my $out, '>', $outfile or die "Can't write to $outfile: $!";

    for my $i (0 .. $#t - 1) {
        my $rec = $lines[$i];

        # Write original line
        my @orig = ();
        push @orig, 'image', $rec->{'image'} if exists $rec->{'image'};
        push @orig, 'w',     $rec->{'w'}     if exists $rec->{'w'};
        push @orig, 'h',     $rec->{'h'}     if exists $rec->{'h'};
        push @orig, 'x',     $rec->{'x'},    'y', $rec->{'y'};
        print $out join(',', @orig), "\n";

        # Interpolated points (exactly $steps intermediates)
        for my $s (1 .. $steps) {
            my $tt = $t[$i] + $s / ($steps + 1);
            my $xi = int($spline_x->evaluate($tt) + 0.5);
            my $yi = int($spline_y->evaluate($tt) + 0.5);

            my @mid = ();
            push @mid, 'image', $rec->{'image'} if exists $rec->{'image'};
            push @mid, 'w',     $rec->{'w'}     if exists $rec->{'w'};
            push @mid, 'h',     $rec->{'h'}     if exists $rec->{'h'};
            push @mid, 'x',     $xi,            'y', $yi;
            print $out join(',', @mid), "\n";
        }
    }

    # Last original point
    my $last = $lines[-1];
    my @lastline = ();
    push @lastline, 'image', $last->{'image'} if exists $last->{'image'};
    push @lastline, 'w',     $last->{'w'}     if exists $last->{'w'};
    push @lastline, 'h',     $last->{'h'}     if exists $last->{'h'};
    push @lastline, 'x',     $last->{'x'},    'y', $last->{'y'};
    print $out join(',', @lastline), "\n";

    close $out;
    return 1;
}
