import { existsSync } from "fs";

import { Article, asyncLoadJSON, asyncSaveJSON, leanArticle, leanCard, MCMDB, onlyUnique } from "../lib";

async function run() {
  if (process.argv.length < 3) {
    console.error("Usage: yarn fetch <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`);

  let cards = articles
    .filter(art => art.idProduct in db)
    .map(art => {
      const card = db[art.idProduct];
      return {
        ...leanArticle(art),
        ...leanCard(card)
      };
    });

  let valid = cards
    .filter(
      c =>
        (c.language == "Italian" || c.language == "English") &&
        c.price <= 0.1 &&
        (c.rarity == "rare" || c.rarity == "mythic")
    )
    .filter(onlyUnique);
  let netprice = valid.reduce((a, c) => (a += c.price), 0);
  console.log(
    `Found ${
      valid.length
    } cards (rare or mythic) <= € 0.10 (IT/EN), price to buy all: € ${netprice.toFixed(
      2
    )}.`
  );
  await asyncSaveJSON(
    `${uid}-filtered-cards.json`,
    valid.sort((a, b) => a.edhrecRank - b.edhrecRank)
  );
}

run();
