package OddMuse;
use HTML::WikiConverter;
use File::Slurper qw(read_text write_text);
use Encode;
use utf8;
no warnings 'redefine';
no warnings 'once';
our $RunCGI = 0;
do './wiki.pl' or die "Cannot load ./wiki.pl";
Init();

my $wc = new HTML::WikiConverter(
  dialect => 'Markdown',
  escape_entities => 0,
  wiki_uri => '/view/',
  base_uri => "$ScriptName/",
  link_style => 'inline',
  image_style => 'inline',
  md_extra => 1);

sub nop { }
*PrintJournal = \&nop;
*SearchTitleAndBody = \&nop;
*HTML::WikiConverter::Markdown::_link = \&_link;

sub _link {
  my ( $self, $node, $rules ) = @_;

  my $url   = $self->_abs2rel( $node->attr('href') || '' );
  my $text  = $self->get_elem_contents($node);
  my $title = $node->attr('title') || '';

  return sprintf "[%s](%s \"%s\")", $text, $url, $title if $title;
  return sprintf "[%s](%s)", $text, $url;
}

sub table {
  my $str = shift;
  my $sep = $str;
  $sep =~ s/[^|]+/:--:/g;
  return "$str\n$sep";
}

sub img {
  my ($title, $id) = @_;
  my ($type) = PageIsUploadedFile($id);
  print STDERR "? $id\n" unless $type;
  my $ext = $StaticMimeTypes{$type};
  return "![$title]($id.$ext)";
}

sub tag {
  $_ = shift;
  s/ /_/g;
  return "#$_";
}

die "Where is the wiki directory?\n" unless -d "wiki";
mkdir "lost" unless -d "lost";
my @pages = AllPagesList();
@pages = grep(/^$CommentsPrefix/, @pages);
for my $id (@pages) {
  OpenPage($id);
  my ($type) = TextIsFile($Page{text});
  if ($type) {
    my $ext = $StaticMimeTypes{$type};
    print STDERR "$ext $id\n";
  } else {
    print STDERR "md $id\n";
    my $html = ToString(\&PrintPageHtml);
    my %escapes;
    my $key = 1;
    my $ESC = "\x1b";
    # escape SVG
    $html =~ s/(<svg.*?>.*?<\/svg>)/$escapes{$key} = $1; $ESC . ($key++) . ";"/seg;
    # convert to Markdown
    my $md = "# " . NormalToFree($id) . "\n\n" . decode_utf8($wc->html2wiki(encode_utf8($html)));
    # restore escapes
    $md =~ s/$ESC(\d+);/$escapes{$1}/ge;
    # fix tags
    $md =~ s/\[\\?#?(.*?)\]\(\.\.\/wiki\?action=tag;id=(?:%23)?(\S+) "Tag"\)/tag($1)/g;
    # fix images
    $md =~ s/\[!\[([^]]*)\]\($ScriptName\/download\/(\S+) "\1"\)\]\(\2\)/img($1, $2)/ge;
    # fix tables
    $md =~ s/\n\n(\|.*)/"\n\n" . table($1)/ge;
    # fix title
    $md =~ s/# Comments on.*/## Comments\n\n(Please contact me if you want to remove your comment.)\n\n⁂\n\n/m;
    # append to real file, while maintaining the timestamp
    $id =~ s/^$CommentsPrefix//;
    my $fn = "wiki/$id.md";
    if (-f $fn) {
      my $old = read_text($fn);
      my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
          $atime,$mtime,$ctime,$blksize,$blocks)
          = stat($fn);
      rename($fn, $fn . '~');
      write_text($fn, "$old\n\n$md");
      utime($atime, $mtime, $fn);
    } else {
      write_text("lost/$id.md", $md)
    }
  }
}