// encode_order: writes the article order residual of cmix-neif-1.0.
//
// cmix-neif-1.0 ships its article order as a rule plus a residual
// (src/readalike_prepr/order_codec.h, src/readalike_prepr/data/new_article_order).
// The 1.0 source tree contains only the decoder, ord::DecodeOrderV3. This
// driver is the matching encoder. It uses the 1.0 page scan (ord::Extractor),
// the 1.0 feature weights (ord::Idf, ord::ORDV3_DFMAX) and the 1.0 cluster
// vote (ord::ORDV3Vote), so encoder and decoder apply the same rule. At the
// end it decodes its own output with ord::DecodeOrderV3 and compares.
//
// Input order: unit numbers, one per line, in the format of fx2-cmix
// src/readalike_prepr/data/new_article_order, with the calendar pages still
// at their places (step3_project_pages.txt of order_steps.py). The residual
// does not follow from the final order alone: its clusters are the
// descending runs of this input order, and where the calendar pages are
// taken out, two neighbouring runs may continue to descend (twice in 1.0)
// and still remain two clusters.
//
// Steps:
//   (a) .main from enwik9, as "comp9 -e" does in front of the reordering.
//   (b) Page scan of .main: class, calendar key and features of every
//       non-redirect page (unit), as in ord::DecodeOrderV3.
//   (c) Input order -> parts. Units missing from the input order are
//       excluded. Along the input order the classes must form
//       normal | census | image | normal | disambiguation | geographic |
//       personal-name, each class block by descending unit number. n_split =
//       number of normal pages (without calendar pages) in front of the
//       census block.
//   (d) Calendar rule: a normal page with a calendar title leaves the normal
//       part; the decoder writes all of them as one block sorted by the key
//       of the title. n_kal = number of remaining normal pages in front of the
//       first day page that is directly followed by another day page.
//   (e) Clusters: the normal pages of the input order are cut into maximal
//       runs of descending unit numbers; the calendar pages are then removed
//       from the runs.
//   (f) Symbols: for each normal page in ascending unit order the 1.0 vote
//       ranks the clusters already seen; the symbol is the rank of the
//       page's cluster (1 = best), 0 for the first page of a new cluster,
//       or ORDV3_R_ESC + cluster for a cluster without a vote or with a rank
//       of ORDV3_R_ESC or more.
//   (g) Residual file: varints in the order that ord::ParseResidualV3 reads.
//   (h) Roundtrip: ord::DecodeOrderV3 on the residual must give the input
//       order with the calendar block moved (expected order of step d).
//
// Build against the unmodified cmix-neif-1.0 source tree (encode_order.sh
// does all of this):
//   g++ -O2 -std=c++17 -I <tree>/src -o encode_order encode_order.cpp
// Run in an empty directory:
//   ./encode_order <enwik9> <order_in> <residual_out> <order_out>
// order_out is the decoded order (unit numbers, fx2 format).
// All numbers are 0-based; a unit number counts the non-redirect pages.
//
// License: GNU GPL version 3, like cmix-neif-1.0, whose headers it includes.

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <fstream>
#include <string>
#include <unordered_map>
#include <vector>

#include "readalike_prepr/order_codec.h"       // ord::
#include "readalike_prepr/phda9_preprocess.h"  // census_file()
#include "readalike_prepr/misc.h"              // split4Comp(), cmtidx_inplace()

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

static void PutVarint(std::vector<uint8_t>* b, int64_t x) {
  uint64_t v = (uint64_t)x;
  while (v >= 0x80) { b->push_back((uint8_t)(v | 0x80)); v >>= 7; }
  b->push_back((uint8_t)v);
}

static bool ReadNumbers(const char* path, std::vector<int>* v) {
  FILE* f = fopen(path, "r");
  if (!f) return false;
  int x;
  while (fscanf(f, "%d", &x) == 1) v->push_back(x);
  fclose(f);
  return true;
}

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;
}

static bool WriteBytes(const char* path, const std::vector<uint8_t>& b) {
  FILE* f = fopen(path, "wb");
  if (!f) return false;
  bool ok = fwrite(b.data(), 1, b.size(), f) == b.size();
  return fclose(f) == 0 && ok;
}

// Group of a calendar key (ord::KalKey): 0 year, 1 decade, 2 century,
// 3 millennium, 4 day, 5 month, 6 month of a year, 7 deaths/births in a year.
static int KalGroup(int64_t key) { return (int)(key >> 32); }

int main(int argc, char** argv) {
  if (argc != 5) {
    fprintf(stderr, "usage: encode_order <enwik9> <order_in> <residual_out> <order_out>\n");
    return 2;
  }

  // (a) .main: the steps of "comp9 -e" in front of reorder(), as in
  // derive_order.cpp. The rule reads its features from this file.
  if (!census_file(argv[1], ".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) Page scan, as in ord::DecodeOrderV3 (there with the residual's
  // corrections; this encoder writes none).
  std::vector<int> klass;                          // per unit, extractor class 0..5
  std::vector<int64_t> kal;                        // per unit, calendar key or -1
  std::vector<std::vector<uint64_t>> raw_feats;    // per unit, hashed features
  {
    std::ifstream in(".main");
    if (!in) return Fail("cannot read .main");
    std::string line;
    ord::Extractor ex;
    ord::PageScan ps;
    while (std::getline(in, line)) {
      if (!ex.Line(line, &ps)) continue;
      if (ps.is_redirect) continue;
      klass.push_back(ps.klass);
      kal.push_back(ps.kal);
      raw_feats.push_back(std::move(ps.feats));
    }
  }
  const int n_units = (int)klass.size();

  // (c) Input order -> excluded units, class layout, n_split.
  std::vector<int> input;
  if (!ReadNumbers(argv[2], &input)) return Fail("cannot read order_in");
  std::vector<char> listed(n_units, 0);
  for (int u : input) {
    if (u < 0 || u >= n_units) return Fail("unit number out of range");
    if (listed[u]) return Fail("unit listed twice");
    listed[u] = 1;
  }
  std::vector<int> excl;
  for (int u = 0; u < n_units; ++u)
    if (!listed[u]) excl.push_back(u);
  // Stage of each position: 0 normal | 1 census | 2 image | 3 normal |
  // 4 disambiguation | 5 geographic | 6 personal-name disambiguation.
  static const int kStage[6][2] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {5, 5}, {6, 6}};
  int stage = 0, prev_class = -1, prev_unit = -1;
  int64_t n_split = -1;
  int64_t normal_seen = 0;                         // non-calendar normal pages so far
  for (int u : input) {
    const int k = klass[u];
    const int s0 = kStage[k][0], s1 = kStage[k][1];
    int s = (stage <= s0) ? s0 : s1;
    if (s < stage) return Fail("input order does not have the class layout of the rule");
    if (k != 0 && k == prev_class && u > prev_unit)
      return Fail("class block not in descending unit order");
    if (s >= 1 && n_split < 0) n_split = normal_seen;
    stage = s;
    if (k == 0 && kal[u] < 0) ++normal_seen;
    prev_class = k;
    prev_unit = u;
  }
  if (n_split < 0) n_split = 0;

  // (d) Calendar rule. Normal sequence of the input order (class 0), the
  // calendar pages taken out, n_kal at the first day page that is followed
  // by another day page.
  std::vector<int> normal_in;                      // class-0 pages, input order
  for (int u : input)
    if (klass[u] == 0) normal_in.push_back(u);
  auto is_cal = [&](int u) { return kal[u] >= 0; };
  auto is_day = [&](int u) { return kal[u] >= 0 && KalGroup(kal[u]) == 4; };
  int64_t n_kal = -1;
  {
    int64_t before = 0;
    for (size_t i = 0; i < normal_in.size(); ++i) {
      const int u = normal_in[i];
      if (n_kal < 0 && is_day(u) && i + 1 < normal_in.size() && is_day(normal_in[i + 1]))
        n_kal = before;
      if (!is_cal(u)) ++before;
    }
  }
  std::vector<uint64_t> cal_block;                 // key << 18 | unit, as in the decoder
  for (int u = 0; u < n_units; ++u)
    if (klass[u] == 0 && listed[u] && is_cal(u)) cal_block.push_back((uint64_t)kal[u] << 18 | (uint64_t)u);
  std::sort(cal_block.begin(), cal_block.end());
  if (cal_block.empty()) n_kal = 0;
  if (n_kal < 0) return Fail("no place for the calendar block");

  // Normal units without the calendar pages: dense ids in ascending unit order.
  std::vector<int> uni;                            // dense id -> unit
  std::vector<int> dense_of(n_units, -1);
  for (int u = 0; u < n_units; ++u)
    if (klass[u] == 0 && listed[u] && !is_cal(u)) { dense_of[u] = (int)uni.size(); uni.push_back(u); }
  const int32_t n = (int32_t)uni.size();

  // (e) Clusters: maximal descending runs of normal_in, calendar pages removed.
  std::vector<int32_t> axis_of_dense(n, -1);       // dense id -> cluster (axis rank)
  std::vector<int32_t> nrm;                        // target normal part, dense ids
  int32_t n_axis = 0;
  {
    int32_t run = -1, last_run = -1;
    for (size_t i = 0; i < normal_in.size(); ++i) {
      const int u = normal_in[i];
      if (i == 0 || u > normal_in[i - 1]) ++run;
      if (is_cal(u)) continue;
      if (run != last_run) { ++n_axis; last_run = run; }
      axis_of_dense[dense_of[u]] = n_axis - 1;
      nrm.push_back(dense_of[u]);
    }
  }
  if ((int32_t)nrm.size() != n) return Fail("normal part size");

  // Features as in ord::DecodeOrderV3: DF cap, feature index, posting lists
  // (ascending dense ids), integer IDF.
  std::vector<std::vector<uint64_t>> feats(n);
  for (int32_t t = 0; t < n; ++t) feats[t].swap(raw_feats[uni[t]]);
  std::unordered_map<uint64_t, int32_t> fid;
  {
    std::unordered_map<uint64_t, int32_t> df;
    df.reserve((size_t)n * 16);
    for (int32_t t = 0; t < n; ++t)
      for (uint64_t f : feats[t]) ++df[f];
    fid.reserve(df.size());
    for (auto& kv : df)
      if (kv.second <= ord::ORDV3_DFMAX) fid.emplace(kv.first, (int32_t)fid.size());
  }
  std::vector<std::vector<int32_t>> post(fid.size());
  std::vector<int64_t> idf(fid.size());
  for (int32_t t = 0; t < n; ++t) {
    std::vector<uint64_t> kept;
    for (uint64_t f : feats[t]) {
      auto it = fid.find(f);
      if (it != fid.end()) { post[it->second].push_back(t); kept.push_back((uint64_t)it->second); }
    }
    feats[t].swap(kept);
  }
  for (auto& kv : fid) idf[kv.second] = ord::Idf((uint64_t)n, (uint64_t)post[kv.second].size());

  // Cluster ids: the decoder numbers clusters in order of their first page
  // in ascending unit order (seq id); "starts" lists the seq id of each
  // cluster in target order.
  std::vector<int32_t> seq_of_axis(n_axis, -1);
  std::vector<int32_t> clus_target(n, -1);         // dense id -> seq id
  {
    int32_t ns = 0;
    for (int32_t t = 0; t < n; ++t) {
      const int32_t a = axis_of_dense[t];
      if (seq_of_axis[a] < 0) seq_of_axis[a] = ns++;
      clus_target[t] = seq_of_axis[a];
    }
  }

  // (f) Symbols, mirror image of the decoding loop of ord::DecodeOrderV3.
  ord::ORDV3Vote V;
  if (!V.Init(n_axis, seq_of_axis)) return Fail("cluster sequence");
  std::vector<int32_t> clus(n, -1);                // seq ids of the pages done
  std::vector<int64_t> syms(n);
  int32_t n_seen = 0;
  long n_new = 0, n_rank = 0, n_esc = 0;
  for (int32_t t = 0; t < n; ++t) {
    V.Score(t, feats[t], post, idf, clus, n_seen);
    V.Recent(t, clus);
    const int32_t cl = clus_target[t];
    int64_t sym;
    if (cl == n_seen) {                            // first page of a new cluster
      sym = 0; ++n_seen; ++n_new;
    } else {
      bool voted = false; int64_t sc = 0;
      for (int32_t x : V.cltouch)
        if (x == cl) { voted = true; sc = V.clscore[(size_t)x]; break; }
      int64_t r = 0;                               // rank under the decoder's comparator
      if (voted)
        for (int32_t x : V.cltouch) {
          const int64_t s = V.clscore[(size_t)x];
          if (s > sc || (s == sc && x < cl)) ++r;
        }
      if (voted && r + 1 < ord::ORDV3_R_ESC) { sym = r + 1; ++n_rank; }
      else { sym = ord::ORDV3_R_ESC + cl; ++n_esc; }
    }
    syms[t] = sym;
    clus[t] = cl;
    V.Commit(cl);
  }

  // (g) Residual file.
  std::vector<uint8_t> out;
  PutVarint(&out, (int64_t)excl.size());
  int64_t last = -1;
  for (int e : excl) { PutVarint(&out, e - last); last = e; }
  PutVarint(&out, 0);                              // no class corrections
  PutVarint(&out, n_split);
  PutVarint(&out, n_kal);
  PutVarint(&out, n_axis);
  for (int32_t s : seq_of_axis) PutVarint(&out, s);
  for (int64_t s : syms) PutVarint(&out, s);
  PutVarint(&out, ord::ORDV3_TUNE_TAG);            // form tag of the residual
  if (!WriteBytes(argv[3], out)) return Fail("cannot write residual_out");

  // (h) Expected order: the input order without the calendar pages, the
  // calendar block in front of the n_kal-th remaining normal page (in front
  // of the census block if that comes first, behind the last normal page if
  // n_kal is the number of normal pages).
  std::vector<int> expected;
  {
    int64_t i_norm = 0;
    bool cal_done = false;
    for (int u : input) {
      const bool normal = (klass[u] == 0);
      if (normal && is_cal(u)) continue;
      if (!cal_done && i_norm == n_kal && (normal || klass[u] <= 2)) {
        for (uint64_t e : cal_block) expected.push_back((int)(e & 0x3FFFF));
        cal_done = true;
      }
      if (normal) ++i_norm;
      expected.push_back(u);
      if (!cal_done && i_norm == n && n_kal == n) {
        for (uint64_t e : cal_block) expected.push_back((int)(e & 0x3FFFF));
        cal_done = true;
      }
    }
  }
  std::vector<int> decoded;
  if (!ord::DecodeOrderV3(argv[3], ".main", &decoded)) return Fail("roundtrip: decoding failed");
  if (decoded != expected) return Fail("roundtrip: decoded order differs");
  if (!WriteNumbers(argv[4], decoded)) return Fail("cannot write order_out");

  fprintf(stderr,
          "encode_order: units %d, listed %zu, excluded %zu; normal %d in %d clusters,"
          " calendar block %zu; n_split %lld, n_kal %lld; symbols new %ld, rank %ld,"
          " escape %ld; residual %zu B; roundtrip passed\n",
          n_units, input.size(), excl.size(), n, n_axis, cal_block.size(),
          (long long)n_split, (long long)n_kal, n_new, n_rank, n_esc, out.size());
  return 0;
}
