#!/usr/bin/env perl
use 5.010;
use strict;
use warnings;

use Getopt::Long;
use Game::Reversi::Terminal;

my %opt = (level => 3, variant => 'historic', colour => 'b', seed => 'reversi');
GetOptions(\%opt, 'level=i', 'variant=s', 'colour=s', 'seed=s', 'ascii', 'help|h')
	or usage(2);
usage(0) if $opt{help};

$opt{colour} = 'b' if lc $opt{colour} eq 'dark'  || lc $opt{colour} eq 'black';
$opt{colour} = 'w' if lc $opt{colour} eq 'light' || lc $opt{colour} eq 'white';

my $terminal = eval {
	Game::Reversi::Terminal->new(
		level => $opt{level}, variant => $opt{variant},
		colour => $opt{colour}, seed => $opt{seed},
		ascii => $opt{ascii});
};
if (!$terminal) {
	my $why = $@ || "could not start\n";
	$why =~ s/ at \S+ line \d+\.?\n?\z//;
	print STDERR "reversi: $why\n";
	exit 2;
}

my $result = $terminal->start;
exit 0 unless $result;
exit 0 if !defined $result->winner;
exit 0 if $result->winner eq $opt{colour};
exit 1;

sub usage {
	my ($status) = @_;
	my $fh = $status ? \*STDERR : \*STDOUT;
	print {$fh} <<'USAGE';
reversi - play Reversi in a terminal

    reversi [--level 1..5] [--variant historic|othello]
            [--colour b|w] [--seed STRING] [--ascii]

  --level    how hard the opponent is, 1 to 5. Default 3.
  --variant  historic, the real Reversi opening where the players place the
             first four discs themselves, or othello, where those four are
             already down. Default historic.
  --colour   b to play dark and move first, w to play light. Default b.
  --seed     makes a game reproducible, and decides how the bot opens.
  --ascii    X and O on a plain grid, for a terminal without box characters.

  Exit status is 0 if you won or tied, 1 if you lost, 2 for a bad option.
USAGE
	exit $status;
}
