// derive_order: the article order of cmix-neif-1.0 as plain page numbers.
//
// cmix-neif-1.0 does not ship its article order as a list. It ships a rule
// (the order extractor in src/readalike_prepr/order_codec.h) plus a residual
// (src/readalike_prepr/data/new_article_order) and rebuilds the order from
// enwik9 at compression time (README of cmix-neif-1.0, section 4.5). This
// driver calls the 1.0 functions in the order in which the article order
// comes about and writes the result as lists:
//   (a) .main from enwik9, the input that the 1.0 compressor reorders;
//   (b) residual + rule -> sequence of unit numbers (listed pages);
//   (c) unit number -> page index, as in fx2-cmix's article_remap;
//   (d) unlisted pages (redirects and 38 excluded pages) to the front;
//   (e) output files.
// A final cross-check runs the 1.0 reorder() itself and compares the page
// sequence of the .main_reordered it writes with the result of (d).
//
// Build against the unmodified cmix-neif-1.0 source tree (derive_order.sh
// does all of this):
//   g++ -O2 -std=c++17 -I <tree>/src -o derive_order derive_order.cpp
// Run in an empty directory that holds .new_article_order, a copy of
// <tree>/src/readalike_prepr/data/new_article_order:
//   ./derive_order <enwik9> <pages_out> <pages_fx2_out> <units_out>
// All numbers are 0-based. A page index counts the <page> elements of enwik9
// in file order; a unit number counts the non-redirect pages.
//
// License: GNU GPL version 3, like cmix-neif-1.0, whose headers it includes.

#include "readalike_prepr/article_reorder.h"   // reorder(), loadFile(), ord::
#include "readalike_prepr/phda9_preprocess.h"  // wfgets(), census_file()
#include "readalike_prepr/misc.h"              // split4Comp(), cmtidx_inplace()

#include <fstream>
#include <string>
#include <unordered_map>
#include <vector>

static int Fail(const char* what) {
  fprintf(stderr, "derive_order: %s\n", what);
  return 1;
}

static bool WriteNumbers(const char* path, const std::vector<int>& v) {
  FILE* f = fopen(path, "wb");
  if (!f) return false;
  for (int x : v) fprintf(f, "%d\n", x);
  return fclose(f) == 0;
}

// Pages of a file in file order (page id = first <id> after <page>), parsed by
// loadFile() of article_reorder.h, the parser that reorder() uses.
static std::vector<Accumulator> Pages(const char* path) {
  vec.clear();
  loadFile(path);
  std::vector<Accumulator> pages(vec);
  vec.clear();
  freeLines();
  return pages;
}

// (c) page_of_unit[k] = page index of the k-th non-redirect page of .main.
// A page is a redirect if one of its lines starts with one of the five
// prefixes below; prefixes and page delimiter are those of reorder() in
// cmix-neif-1.0 and of article_remap.cpp in fx2-cmix.
static std::vector<int> PageOfUnit(const char* main_path, int* n_pages,
                                   int* n_redirects) {
  static const char* const kRedirectPrefixes[] = {
      "      <text xml:space=\"preserve\">#REDIRECT",
      "      <text xml:space=\"preserve\">#redirect",
      "      <text xml:space=\"preserve\">#Redirect",
      "      <text xml:space=\"preserve\">#REdirect",
      "      <text xml:space=\"preserve\">{{softredirect"};
  std::vector<int> page_of_unit;
  int page = -1;
  bool redirect = false;
  *n_redirects = 0;
  auto close_page = [&]() {
    if (page < 0) return;
    if (redirect) ++*n_redirects;
    else page_of_unit.push_back(page);
  };
  std::ifstream in(main_path);
  std::string line;
  while (std::getline(in, line)) {
    if (line == "  <page>") {
      close_page();
      ++page;
      redirect = false;
      continue;
    }
    for (const char* prefix : kRedirectPrefixes)
      if (line.rfind(prefix, 0) == 0) { redirect = true; break; }
  }
  // reorder() never closes the last page; the last page of .main is a
  // redirect, so the mapping is the same.
  close_page();
  *n_pages = page + 1;
  return page_of_unit;
}

int main(int argc, char** argv) {
  if (argc != 5) {
    fprintf(stderr,
            "usage: derive_order <enwik9> <pages_out> <pages_fx2_out> <units_out>\n");
    return 2;
  }
  const char* enwik9 = argv[1];

  // (a) .main: the steps of "comp9 -e" in front of reorder() (runner.cpp).
  // The census transform replaces numbers of the census pages that follow
  // from other numbers of the same page by control bytes; split4Comp cuts
  // off the header (.intro, first 29 lines) and the tail (.coda, with the
  // last, truncated page of enwik9); the comment index adds one index line to
  // some pages. The order rule reads its features from this file, so it is
  // reproduced exactly; page boundaries and redirect lines stay as in enwik9.
  if (!census_file(enwik9, ".census_prepr", 1)) return Fail("census transform failed");
  split4Comp(".census_prepr");
  remove(".census_prepr");
  if (!cmtidx_inplace(".main", ".cmtidx_main", 1)) return Fail("comment index failed");

  // (b) Residual + rule -> unit numbers in coding order. ord::DecodeOrderV3
  // scans every non-redirect page of .main and
  //   - puts census, image, disambiguation, geographic and personal-name
  //     disambiguation pages into classes, recognised with the strings of
  //     Byron Knoll's manual sort step of the fx2-cmix order (the residual
  //     corrects single pages and excludes 38 pages from the list);
  //   - takes the calendar pages (title is a year, decade, century,
  //     millennium, day, month, month of a year or list of deaths of a year)
  //     out and writes them as one block, sorted by a key from the title;
  //   - for the other pages lets features (title tokens, links and content
  //     words of the first 600 characters, categories, templates) vote for
  //     clusters in integer arithmetic; per page the residual names the
  //     cluster relative to the vote, plus the sequence of the clusters;
  //   - assembles: the clusters in residual order (pages inside a cluster by
  //     descending unit number), the calendar block and the census and image
  //     pages at positions given by the residual (census and image in front
  //     of the block of Wikipedia: pages), then disambiguation, geographic
  //     and personal-name disambiguation pages; each class by descending
  //     unit number.
  std::vector<int> units;
  if (!ord::DecodeOrderV3(".new_article_order", ".main", &units))
    return Fail("order reconstruction failed");

  // (c) Unit number -> page index.
  int n_pages = 0, n_redirects = 0;
  const std::vector<int> page_of_unit = PageOfUnit(".main", &n_pages, &n_redirects);
  if (n_pages != NUM_OF_ARTICLES) return Fail(".main page count");
  std::vector<int> listed;
  std::vector<char> is_listed(n_pages, 0);
  for (int u : units) {
    if (u < 0 || u >= (int)page_of_unit.size()) return Fail("unit number out of range");
    const int page = page_of_unit[u];
    if (is_listed[page]) return Fail("page listed twice");
    is_listed[page] = 1;
    listed.push_back(page);
  }

  // (d) Unlisted pages: the redirects and the excluded pages, by ascending
  // page index. fx2-cmix appends them behind the listed pages; cmix-neif-1.0
  // writes them in front (redirect block).
  std::vector<int> unlisted;
  for (int p = 0; p < n_pages; ++p)
    if (!is_listed[p]) unlisted.push_back(p);
  std::vector<int> order_fx2(listed);
  order_fx2.insert(order_fx2.end(), unlisted.begin(), unlisted.end());
  std::vector<int> order_10(unlisted);
  order_10.insert(order_10.end(), listed.begin(), listed.end());

  // Page index in .main = page index in enwik9: .intro holds no page.
  const std::vector<Accumulator> enwik9_pages = Pages(enwik9);
  const std::vector<Accumulator> main_pages = Pages(".main");
  if ((int)main_pages.size() != n_pages || enwik9_pages.size() < main_pages.size())
    return Fail("page count");
  for (size_t i = 0; i < main_pages.size(); ++i)
    if (enwik9_pages[i].id != main_pages[i].id) return Fail(".main and enwik9 pages differ");

  // (e) Output.
  if (!WriteNumbers(argv[2], order_10)) return Fail("cannot write pages_out");
  if (!WriteNumbers(argv[3], order_fx2)) return Fail("cannot write pages_fx2_out");
  if (!WriteNumbers(argv[4], units)) return Fail("cannot write units_out");

  // Cross-check: reorder() of cmix-neif-1.0 writes .main_reordered; its page
  // sequence (by page id) must be order_10.
  reorder();
  const std::vector<Accumulator> reordered = Pages(".main_reordered");
  if (reordered.size() != order_10.size()) return Fail("cross-check: page count");
  for (size_t i = 0; i < reordered.size(); ++i)
    if (reordered[i].id != main_pages[order_10[i]].id)
      return Fail("cross-check: .main_reordered differs");

  fprintf(stderr,
          "derive_order: pages %d (redirects %d), listed %zu, unlisted %zu"
          " (redirects + %zu excluded); cross-check with reorder() passed\n",
          n_pages, n_redirects, listed.size(), unlisted.size(),
          unlisted.size() - (size_t)n_redirects);
  return 0;
}
