use Modern::Perl;
use File::Slurper qw(read_text write_text read_dir);
use Algorithm::Diff;
use Encode;
binmode(STDOUT, ":utf8");
my $data = read_text("wiki/Names_Bookmarks.md");
my %names;
while ($data =~ /\[([^\]]+)\]\(([^\)]+)\)/g) {
  $names{$1} = $2;
}
for my $fn (read_dir("wiki")) {
  next if $fn eq "Names_Bookmarks.md";
  next if $fn !~ /\.md$/;
  my $old = read_text("wiki/$fn");
  my $text = $old;
  my $ch = 0;
  for my $name (keys %names) {
    my $name_re = quotemeta($name);
    my $id = $name;
    $id =~ s/ /_/g;
    my $id_re = quotemeta($id);
    $ch += $text =~ s/\.\.\/wiki\?action=edit;id=$id_re "Click to edit this page"/$names{$name}/g;
    $ch += $text =~ s/\[($name_re)\]\(\.\.\/wiki\?action=edit;id=$id_re "Click to edit this page"/$names{$name}/g;
  }
  next unless $ch;
  say decode_utf8($fn);
  if (@ARGV > 0 && $ARGV[0] eq '-confirm') {
    write_text("wiki/$fn~", $old);
    write_text("wiki/$fn", $text);
    next;
  }
  my $diff = Algorithm::Diff->new( [split(/\n/, $old)], [split(/\n/, $text)] );
  $diff->Base( 1 );   # Return line numbers, not indices
  while(  $diff->Next()  ) {
    next   if  $diff->Same();
    my $sep = '';
    if(  ! $diff->Items(2)  ) {
      printf "%d,%dd%d\n",
          $diff->Get(qw( Min1 Max1 Max2 ));
    } elsif(  ! $diff->Items(1)  ) {
      printf "%da%d,%d\n",
          $diff->Get(qw( Max1 Min2 Max2 ));
    } else {
      $sep = "---\n";
      printf "%d,%dc%d,%d\n",
          $diff->Get(qw( Min1 Max1 Min2 Max2 ));
    }
    print "< $_"   for  $diff->Items(1);
    print $sep;
    print "> $_"   for  $diff->Items(2);
  }
}