#!/usr/bin/perl

use strict;
use warnings;
use AI::MicroStructure;
use Getopt::Long;

my $usage = << 'EOT';
Usage: metafy [options] [from:]to [file]
Available options:
  --in-place     : force in-place edit (clobbers the old files)
  --force-random : force target words randomisation
  --help         : print this message and exit
  --version      : print version information and exit
  --themes       : print the list of themes and exit
  --verbose      : print the translations list afterwards
EOT

my %conf = (
    'force-random' => 0,
    verbose        => 1,
);
GetOptions( \%conf, 'version', 'themes', 'help', 'verbose|v', 'force-random',
'in-place')
  or die $usage;

# find out the themes name
die "No theme given\n\n$usage" unless @ARGV;
($conf{from}, $conf{to}) = split /:/, shift, 2;
$conf{to} = $conf{from} unless $conf{to};

# find the themes/categories
for my $t (qw( from to )) {
    my ($theme, $category) = split '/', $conf{$t}, 2;
    die "Theme '$theme' does not exist!\n\n"
      . "Available themes: @{[ AI::MicroStructure->themes() ]}\n"
      unless AI::MicroStructure->has_theme($theme);

   @conf{$t, "${t}_category"} = ($theme, $category);
}

# informative options
print STDERR
"metafy your files, using AI::MicroStructure version $AI::MicroStructure::VERSION\n"
  if $conf{version};
print STDERR $usage if $conf{help};
print map "$_\n", AI::MicroStructure->themes if $conf{themes};
exit if $conf{themes} || $conf{version} || $conf{help};

# real processing starts here
my $from =
  AI::MicroStructure->new( $conf{from}, category => $conf{from_category} );
my $to = AI::MicroStructure->new( $conf{to}, category => $conf{to_category} );
my @to = $to->name(0);
my %to;

# find the origin list
my $re_from = qr/\b(@{[join'|', sort $from->name( 0 ) ]})\b/;

# modify files in place
$^I = '' if $conf{'in-place'};

# loop on the files
while(<>) {
    s/$re_from/
        my $repl;
        if ( $conf{'force-random'} ) { push @{ $to{$1} }, $repl = $to->name() }
        else { $repl = $to{$1} ||= shift @to; @to = $to->name(0) if !@to }
        $repl
    /gei;
}
continue { print }

if( $conf{verbose} ) {
    print STDERR "Translations:\n",
      $conf{'force-random'}
      ? map { "\t$_ => @{$to{$_}}\n" } sort keys %to
      : map { "\t$_ => $to{$_}\n" } sort keys %to;
}

__END__


