import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

class RrfWindowReplay {
  record Hit(String id, double score) {}
  record Case(int window, int topK) {}

  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      throw new IllegalArgumentException("Usage: java RrfWindowReplay.java ranks.properties");
    }
    var ranks = new Properties();
    try (var reader = Files.newBufferedReader(Path.of(args[0]))) {
      ranks.load(reader);
    }
    int constant = Integer.parseInt(ranks.getProperty("rankConstant"));
    List<String> bm25 = items(ranks, "bm25");
    List<String> vector = items(ranks, "vector");
    List<String> expected = items(ranks, "expected");
    String manual = "expense-handbook:2";
    System.out.printf("query=%s k=%d expected=%s%n", ranks.getProperty("query"), constant, expected);
    System.out.printf("manual=%s BM25_rank=%d vector_rank=%d%n",
        manual, bm25.indexOf(manual) + 1, vector.indexOf(manual) + 1);

    for (Case test : List.of(new Case(2, 4), new Case(3, 3), new Case(3, 4), new Case(4, 3))) {
      List<Hit> fused = fuse(bm25, vector, constant, test.window());
      List<String> candidates = fused.stream().map(Hit::id).toList();
      if (test.window() == 3 && !candidates.equals(items(ranks, "originalFused"))) {
        throw new IllegalStateException("Replay differs from the original W=3 fusion");
      }
      List<String> output = candidates.stream().limit(test.topK()).toList();
      long found = expected.stream().filter(output::contains).count();
      boolean candidate = candidates.contains(manual);
      String result = candidate ? (output.contains(manual) ? "returned" : "cut_at_topK") : "absent_from_window";
      System.out.printf("%nW=%d K=%d candidates=%d returned=%d%n",
          test.window(), test.topK(), candidates.size(), output.size());
      System.out.printf("manual_rank=%s result=%s evidence=%d/%d%n",
          candidate ? String.valueOf(candidates.indexOf(manual) + 1) : "-", result, found, expected.size());
      for (int i = 0; i < fused.size(); i++) {
        Hit hit = fused.get(i);
        System.out.printf(Locale.ROOT, "%d  %-20s %.8f%n", i + 1, hit.id(), hit.score());
      }
    }
  }

  static List<Hit> fuse(List<String> bm25, List<String> vector, int constant, int window) {
    Map<String, Double> scores = new LinkedHashMap<>();
    for (List<String> lane : List.of(bm25, vector)) {
      for (int index = 0; index < Math.min(window, lane.size()); index++) {
        scores.merge(lane.get(index), 1.0 / (constant + index + 1), Double::sum);
      }
    }
    return scores.entrySet().stream()
        .map(entry -> new Hit(entry.getKey(), entry.getValue()))
        .sorted(Comparator.comparingDouble(Hit::score).reversed().thenComparing(Hit::id))
        .toList();
  }

  static List<String> items(Properties ranks, String key) {
    return Arrays.asList(ranks.getProperty(key).split(","));
  }
}
