import { existsSync } from "fs";

import { asyncLoadJSON, asyncSaveJSON, MCMCard, MCMDB, ScryfallCard, ScryfallDB } from "../lib";

interface JSONSet {
  cards: MCMCard[];
}

type JSONDB = Record<string, JSONSet>;

const mtgjsonFile = "AllPrintings.json";
const scryfallJSONFile = "scryfall-default-cards.json";

async function run() {
  if (!existsSync(mtgjsonFile)) {
    console.error(
      mtgjsonFile +
        " not found. Download from: https://www.mtgjson.com/files/AllPrintings.json"
    );
    process.exit(1);
  }
  if (!existsSync(scryfallJSONFile)) {
    console.error(
      scryfallJSONFile +
        " not found. Download from: https://archive.scryfall.com/json/scryfall-default-cards.json"
    );
    process.exit(1);
  }
  console.info("Loading " + mtgjsonFile);
  const mtgdb = await asyncLoadJSON<JSONDB>(mtgjsonFile);
  console.info("Loading " + scryfallJSONFile);
  const scrydb = await asyncLoadJSON<ScryfallDB>(scryfallJSONFile);
  let scrycards: Record<string, ScryfallCard> = {};
  scrydb.forEach(c => (scrycards[c.id] = c));
  let acc: MCMDB = {};
  for (const set in mtgdb) {
    mtgdb[set].cards.forEach(c => {
      c.set = set;
      if (c.scryfallId in scrycards) {
        c.scryfallUrl = scrycards[c.scryfallId].scryfall_uri;
        if ("image_uris" in scrycards[c.scryfallId]) {
          c.scryfallImageUrl = scrycards[c.scryfallId].image_uris.normal;
        } else if (
          "card_faces" in scrycards[c.scryfallId] &&
          "image_uris" in scrycards[c.scryfallId].card_faces[0]
        ) {
          c.scryfallImageUrl =
            scrycards[c.scryfallId].card_faces[0].image_uris.normal;
        } else {
          console.log(scrycards[c.scryfallId]);
        }
      }
      // Search for scryfall card
      acc[c.mcmId] = c;
    });
  }
  asyncSaveJSON("mcmCards.json", acc);
  console.info("Saved converted info to mcmCards.json. You're ready to go!");
}

run();
