#!/usr/bin/env node
const assert = require("assert");
const path = require("path");
const fs = require("fs/promises");
const sidebars = require("../csb-jp.github.io/sidebars.js");

const docsPath = "csb-jp.github.io/docs";
const bookPath = "books/codesandbox-guidebook";

function flatten(object) {
  const values = (value) =>
    typeof value === "object" ? flatten(value) : [value];
  return Object.values(object).flatMap(values);
}

async function main() {
  const mdFiles = [];

  for (const id of flatten(sidebars)) {
    const file = path.resolve(docsPath, `${id}.md`);
    try {
      await fs.stat(file);
    } catch {
      continue;
    }
    mdFiles.push(file);
  }

  for (const [i, file] of mdFiles.entries()) {
    const chapter = i + 1;
    await fs.copyFile(file, path.resolve(bookPath, `${chapter}.md`));
  }
}

main();