# include <iostream>
# include <fstream>
# include <Game/GameRecord.h>
# include <Moves/SanNotation.h>
# include <Algorithms/HistoryAlphaBeta.h>
# include <Game/PositionalEvaluation.h>
using namespace Alice;
int main(int argc, char* argv[])
{
  if (argc != 2)
    {
      std::cout<<"usage: "<<argv[0]<<" <pgn file>"<<std::endl;
      return -1;
    };
  int games = 0;
  int successes = 0;
  int failures = 0;
  unsigned long long totalNodes = 0;
  std::cout<<"file name: "<<argv[1]<<std::endl;
  std::ifstream input(argv[1]);
  if (!input)
    {
      std::cout<<argv[0]<<": error."<<std::endl;
      std::cout<<"couldnt open "<<argv[1]<<std::endl;
      return -1;
    };
  while(input)
    {
      GameRecord record;
      record.read(input);
      
      games ++;
      std::cout<<"Game number "<<games<<std::endl;
      std::cout<<"read game record"<<std::endl;
      record.printTags();
      if (!record.plyCount())
	continue;
      std::cout<<"White: "<<record.getTag("White")<<std::endl;
      std::cout<<"Black: "<<record.getTag("Black")<<std::endl;
      std::cout<<"ply count: "<<record.plyCount()<<std::endl;
      //continue;
      Game g;
      HistoryAlphaBeta algo(g);
      PositionalEvaluation eval;
      algo.setEvaluation(&eval);
      int ply = 0;
      if (record.getTag("Result") == "0-1")
	{
	  record.getMove(0)->makeOn(g);
	  ply = 1;
	}
      //else
      //continue;
      for (; ply < record.plyCount()-1; ply += 2)
	{
	  // continue;
	  
	  SanNotation san(record.getMove(ply), g);
	  std::cout<<"target move: ";
	  san.printOn(std::cout);
	  std::cout<<std::endl;
	  algo.setGame(g);
	  algo.searchTime(5);
	  totalNodes += algo.nodesSearched();
	  if (*algo.bestMove() == *record.getMove(ply))
	    successes ++;
	  else
	    failures ++;
	  record.getMove(ply)->makeOn(g);
	  record.getMove(ply+1)->makeOn(g);
	  
	};
      char c;
      if (input>>c)
	input.putback(c);
    }
  std::cout<<"total games: "<<games<<std::endl;
  std::cout<<"total nodes: "<<totalNodes<<std::endl;
  std::cout<<"successes: "<<successes<<std::endl;
  std::cout<<"failures:  "<<failures<<std::endl;
  std::cout<<"percentage: "<<100*successes/(successes+failures)<<"%"
	   <<std::endl;
  return 0;
};
