import { existsSync, writeFile } from "fs";

import { Article, asyncLoadJSON, MCMDB } from "../lib";
import { cubeHTML, genCube } from "../lib/cube";

async function run() {
  if (process.argv.length < 3) {
    console.error("Usage: yarn cube <uid>");
    process.exit(1);
    return;
  }
  const uid = process.argv[2];
  const uidCards = `${uid}-cards.json`;
  if (!existsSync("mcmCards.json")) {
    console.error("Card db is missing! Run 'yarn convert-db' first.");
    process.exit(1);
  }
  if (!existsSync(uidCards)) {
    console.error(`Could not find ${uidCards}! Run 'yarn fetch ${uid}' first.`);
    process.exit(1);
  }
  let db = await asyncLoadJSON<MCMDB>("mcmCards.json");
  let articles = await asyncLoadJSON<Article[]>(`${uid}-cards.json`);

  const cubecards = await genCube(db, articles);
  const template = await cubeHTML(uid, cubecards);

  let cubeFile = `${uid}-cube.html`;
  writeFile(cubeFile, template, {}, err => {
    if (err) {
      throw err;
    }
    console.log(`Wrote cube data to ${cubeFile}`);
  });
}

run();
