// Converts raw data from ff14-fish-tracker to JSON files that we can use with serde.
// The only thing that manually needs to be done is to export the variables from said files.
// Run using `node convert-to-json.js`.

import { DATA } from "./data.js";
import { FISH_INFO } from "./fish_data.js";
import fs from "node:fs/promises";
import axios from "axios";
import PQueue from "p-queue";
import minimist from "minimist";

const argv = minimist(process.argv.slice(2));

const result = {
  db_data: DATA,
  fish_entries: FISH_INFO,
};

// For some reason, there are sometimes double-nested `bestCatchPath` attributes?
Object.values(result.db_data.FISH).forEach((fish) => {
  if (fish.bestCatchPath[0] instanceof Array) {
    result.db_data.FISH[fish._id].bestCatchPath = fish.bestCatchPath[0];
  }
});

if (argv.icons) {
  let promises = Object.values(result.db_data.ITEMS).map((item) => async () => {
    if (item.icon !== "") {
      let url = `https://v2.xivapi.com/api/asset?path=ui/icon/${item.icon.toString().slice(0, 3)}000/${item.icon}.tex&format=png`;
      let { data } = await axios.get(url, { responseType: "arraybuffer" });
      let fileData = Buffer.from(data, "binary");
      return fs.writeFile(`./static/icons/${item.icon}.png`, fileData);
    } else {
      return true;
    }
  });

  console.log(`Downloading ${promises.length} icons...`);
  const queue = new PQueue({ concurrency: 5 });
  await queue.addAll(promises);
  console.log("Download complete!");
}

const json = JSON.stringify(result);

await fs.writeFile("data.json", json, { encoding: "utf8" });
console.log("Saved JSON to data.json!");