/*Copyright (c) 2019 Alexis Nasr && Franck Dary

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:i

 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/
/// \file macaon_compute_l_rules.cpp
/// \author Franck Dary
/// @version 1.0
/// @date 2019-04-10

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include "File.hpp"
#include "util.hpp"
#include <boost/program_options.hpp>

namespace po = boost::program_options;

/// @brief Get the list of mandatory and optional program arguments.
///
/// @return The lists.
po::options_description getOptionsDescription()
{
  po::options_description desc("Command-Line Arguments ");

  po::options_description req("Required");
  req.add_options()
    ("fplm,f", po::value<std::string>()->required(),
      "fplm file that contains words and their lemmas")
    ("exceptions,e", po::value<std::string>()->required(),
      "Output filename for exceptions")
    ("rules,r", po::value<std::string>()->required(),
      "Output filename for rules")
    ("threshold,t", po::value<int>()->required(),
      "Number of times a rule must be used in the fplm before it is outputted");

  po::options_description opt("Optional");
  opt.add_options()
    ("help,h", "Produce this help message")
    ("strict,s", "TODO : find what it does")
    ("debug,d", "Print infos on stderr");

  desc.add(req).add(opt);
  return desc;
}

/// @brief Store the program arguments inside a variables_map
///
/// @param od The description of all the possible options.
/// @param argc The number of arguments given to this program.
/// @param argv The values of arguments given to this program.
///
/// @return The variables map
po::variables_map checkOptions(po::options_description & od, int argc, char ** argv)
{
  po::variables_map vm;

  try {po::store(po::parse_command_line(argc, argv, od), vm);}
  catch(std::exception& e)
  {
    std::cerr << "Error: " << e.what() << "\n";
    od.print(std::cerr);
    exit(1);
  }

  if (vm.count("help"))
  {
    std::cout << od << "\n";
    exit(0);
  }

  try {po::notify(vm);}
  catch(std::exception& e)
  {
    std::cerr << "Error: " << e.what() << "\n";
    od.print(std::cerr);
    exit(1);
  }

  return vm;
}

/// @brief Given a fplm file (pairs of word / lemma), compute rules that will transform these words into lemmas, as well as exceptions.
///
/// @param argc The number of arguments given to this program.
/// @param argv[] Array of arguments given to this program.
///
/// @return 0 if there was no crash.
int main(int argc, char * argv[])
{
  auto od = getOptionsDescription();

  po::variables_map vm = checkOptions(od, argc, argv);

  std::string fplmFilename = vm["fplm"].as<std::string>();
  std::string exceptionsFilename = vm["exceptions"].as<std::string>();
  std::string rulesFilename = vm["rules"].as<std::string>();
  int threshold = vm["threshold"].as<int>();
  bool strict = vm.count("strict") == 0 ? false : true;
  bool debug = vm.count("debug") == 0 ? false : true;

  File fplm(fplmFilename, "r");
  char buffer[100000];

  std::map<std::string, std::vector<std::string> > rules;
  while (fscanf(fplm.getDescriptor(), "%[^\n]\n", buffer) == 1)
  {
    auto splited = util::split(buffer, '\t');

    if (splited.size() != 4)
    {
      fprintf(stderr, "ERROR (%s) : fplm line \'%s\' wrong format. Aborting.\n", ERRINFO, buffer);
      exit(1);
    }

    auto form = splited[0];
    auto lemma = splited[2];
    auto rule = util::getRule(form, lemma);

    rules[rule].emplace_back(buffer);
  }

  File rulesFile(rulesFilename, "w");
  File exceptionsFile(exceptionsFilename, "w");

  for (auto & it : rules)
  {
    if ((int)it.second.size() >= threshold)
      fprintf(rulesFile.getDescriptor(), "%s\n", it.first.c_str());
    else
      for (auto & line : it.second)
        fprintf(exceptionsFile.getDescriptor(), "%s\n", line.c_str());
  }

  if (debug)
  {
    for (auto & it : rules)
    {
      fprintf(stderr, "<%s> : %lu\n", it.first.c_str(), it.second.size());
      for (auto & example : it.second)
        fprintf(stderr, "\t<%s>\n", example.c_str());
    }
  }

  return 0;
}