import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

import * as csv from "csv-parse";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export const getCloudASN = async () =>
  new Promise(async (resolve, reject) => {
    const results = [];
    const cloudList = (
      await fs.promises.readFile(path.join(__dirname, "./cloud_list.md"))
    )
      .toString()
      .split("\n");

    fs.createReadStream("./as.csv")
      .pipe(csv.parse({ delimiter: ",", from_line: 2 }))
      .on("data", function ([asn, handle, description]) {
        if (cloudList.includes(handle) || cloudList.includes(description)) {
          results.push({ asn, handle, description });
        }
      })
      .on("end", function () {
        resolve(results);
      })
      .on("error", function (error) {
        console.log(error.message);
        reject(error.message);
      });
  });
