import { schedule } from "node-cron";
import { readFileSync } from "node:fs";
import config from "@/lib/config";
import { initData } from "@/lib/memory";
import { styleText } from "node:util";
import { Worker } from "node:worker_threads";

try {
  console.log(readFileSync(`${import.meta.dirname}/../asciiart.txt`, "utf-8"));
  console.log(JSON.parse(readFileSync(`${import.meta.dirname}/../package.json`, "utf-8")).version);
  if (config.debug) {
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
  
    console.log(styleText(
      ["bgRed", "cyan", "bold"],
      "デバッグモードが有効です",
    ));
  }
  console.log();

  await initData();

  new Worker(`${import.meta.dirname}/feature/earthquake/index.js`);

  console.log("Botが起動しました");
} catch (err: any) {
  console.error("message" in err
    ? err.message
    : err);
  process.exit(1);
}

try {
  schedule("0 * * * *", async () => {
    new Worker(`${import.meta.dirname}/feature/time/index.js`);
  });

  schedule("0 7 * * *", async () => {
    new Worker(`${import.meta.dirname}/feature/weatherNotice.js`, {
      workerData: "scheduledWeatherNotice",
    });
  });

  schedule("0 18 * * *", async () => {
    new Worker(`${import.meta.dirname}/feature/weatherNotice.js`, {
      workerData: "scheduledWeatherNoticeTomorrow",
    });
  });

  schedule(`*/${config.command.interval} * * * *`, async () => {
    new Worker(`${import.meta.dirname}/feature/command/index.js`);
  });

  let hnyWorker: Worker | undefined = undefined;

  schedule("57 59 23 31 12 *", () => {
    hnyWorker = new Worker(`${import.meta.dirname}/feature/hnyNotice.js`);
  });

  schedule("0 0 0 1 1 *", () => {
    hnyWorker?.postMessage("");
  });
} catch (err: any) {
  console.error("message" in err
    ? err.message
    : err);
}