import { existsSync } from "fs";
import { createServer } from "http";

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-dev <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 server = createServer(async (req, res) => {
    const template = await cubeHTML(uid, cubecards);
    res.end(template);
  });

  server.on("clientError", (err, socket) => {
    socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
  });
  server.listen(8000);
}

run();
