import { existsSync } from "fs";

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

async function run() {
  if (process.argv.length < 3) {
    console.error("Usage: yarn buy <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 cards = cubeCards(await genCube(db, articles));

  let types: Record<string, CardItem[]> = {};
  cards.forEach(c => {
    c.subtypes.forEach(t => {
      if (t in types) {
        types[t].push(c);
      } else {
        types[t] = [c];
      }
    });
  });

  console.log("TRIBAL? Top 10 tribes:");
  const entries = Object.entries(types)
    .sort((a, b) => b[1].length - a[1].length)
    .slice(0, 10)
    .forEach(([typ, typcards]) => {
      console.log(
        `  ${typ.padEnd(16, " ")}${typcards.length
          .toString()
          .padStart(3)} cards (${(
          (typcards.length / cards.length) *
          100
        ).toFixed(1)}%)`
      );
    });
}

run();
