#! /usr/bin/perl
use strict;
use warnings;
use CGI;
use JSON::XS;
use lib '..';
use Position;
use IPC::Open2;

our %openings = ();
read_openings();

my $cgi = CGI->new;
my ($chld_out, $chld_in);
my $pid = IPC::Open2::open2($chld_out, $chld_in, "../binlookup", "../open.mtbl", "40");

# Root position. Basically ignore everything except the opening (and later some root game stuff).
my $fen = $cgi->param('fen') // 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
my $pos = Position->from_fen($fen);
my $hex = unpack('H*', $pos->bitpacked_fen);
print $chld_in $hex, "\n";
chomp (my $line = <$chld_out>);

my ($white, $draw, $black, $opening_num, $white_avg_elo, $black_avg_elo, $num_elo, $timestamp, $pgn_start_position, @moves) = split / /, $line;
my $opening = $openings{$opening_num} // 'A00: Start position';

# Explore one move out.
my @json_moves = ();
for my $move (@moves) {
	my ($np, $uci_move) = $pos->make_pretty_move($move);
	my $hex = unpack('H*', $np->bitpacked_fen);
	print $chld_in $hex, "\n";
	my $line = <$chld_out>;
	my ($white, $draw, $black, $opening_num, $white_avg_elo, $black_avg_elo, $num_elo) = split / /, $line;
	push @json_moves, {
		move => $move,
		white => $white * 1,
		draw => $draw * 1,
		black => $black * 1,
		white_avg_elo => $white_avg_elo * 1,
		black_avg_elo => $black_avg_elo * 1,
		num_elo => $num_elo * 1
	};
}

print $cgi->header(-type=>'application/json');
print JSON::XS::encode_json({ moves => \@json_moves, opening => $opening });

sub num {
	my $x = shift;
	return $x->{'white'} + $x->{'draw'} + $x->{'black'};
}

sub read_openings {
	open my $fh, "../openings.txt"
		or die "../openings.txt: $!";
	for my $line (<$fh>) {
		chomp $line;
		my ($hash, $eco, $opening, $variation, $subvariation) = split /\t/, $line;
		if ($variation eq '') {
			$openings{$hash} = $eco . ": " . $opening;
		} else {
			$openings{$hash} = $eco . ": " . $opening . ": " . $variation;
		}
	}
	close $fh;
}
