import * as R from "remeda";

import { readFile } from "../05/part1.js";

const readInput = (...args) =>
  R.pipe(
    readFile(...args),
    (lines) => lines.split("\n\n"),
    R.compact, // remove last line
    R.map((block) => block.split("\n").map((line) => eval(line)))
  );

export const puzzleInput = readInput(import.meta.url, "input");
export const sample = readInput(import.meta.url, "sample");

export function isLessThan(x, y) {
  if ([x, y].every(R.isNumber)) return x < y ? -1 : x == y ? 0 : 1;

  if ([x, y].every(R.isArray)) {
    for (const [a, b] of R.zip(x, y)) {
      const res = isLessThan(a, b);
      if (res !== 0) return res;
    }
    if (x.length === y.length) return 0;
    return x.length < y.length ? -1 : 1;
  }

  return isLessThan(...[x, y].map((z) => (R.isNumber(z) ? [z] : z)));
}

const passthru = (x) => (arg) => {
  x(arg);
  return arg;
};

export default R.createPipe(
  R.map(([x, y]) => isLessThan(x, y)),
  (results) => results.map((value, index) => ({ value, index: index + 1 })),
  R.filter(({ value }) => value !== 1),
  R.map(R.prop("index")),
  (results) => results.reduce((a, b) => a + b)
);