import schedule from "node-schedule";
import { exec } from "node:child_process";

console.log("start ...");

function runTsFile(filePath: string): Promise<void> {
  return new Promise((resolve, reject) => {
    console.log(`Starting: ${filePath}`);
    exec(`bun run ${filePath}`, (error, stdout, stderr) => {
      if (error) {
        console.error(`Execution error: ${error.message}`);
        reject(error);
        return;
      }
      if (stderr) {
        console.error(`Error: ${stderr}`);
      }
      console.log(`Output: ${stdout}`);
      console.log(`Completed: ${filePath}`);
      resolve();
    });
  });
}

// 11시에 실행 - fetch-articles -> fetch-detailAddress -> updateRanging -> sendTelegram
schedule.scheduleJob("0 11 * * *", async () => {
  console.log("Running scheduled jobs at 11 AM");
  try {
    await runTsFile("./fetch-articles.ts");
    await runTsFile("./fetch-detailAddress.ts");
    await runTsFile("./updateRanging.ts");
    await runTsFile("./sendTelegram.ts");
  } catch (error) {
    console.error("Error in 11 AM scheduled job:", error);
  }
});

// 16시에 실행 - fetch-articles -> fetch-detailAddress -> updateRanging -> sendTelegram
schedule.scheduleJob("0 16 * * *", async () => {
  console.log("Running scheduled jobs at 4 PM");
  try {
    await runTsFile("./fetch-articles.ts");
    await runTsFile("./fetch-detailAddress.ts");
    await runTsFile("./updateRanging.ts");
    await runTsFile("./sendTelegram.ts");
  } catch (error) {
    console.error("Error in 4 PM scheduled job:", error);
  }
});

// 16시에 실행 - fetch-articles -> fetch-detailAddress -> updateRanging -> sendTelegram
schedule.scheduleJob("05 21 * * *", async () => {
  console.log("Running scheduled jobs at 4 PM");
  try {
    await runTsFile("./fetch-articles.ts");
    await runTsFile("./fetch-detailAddress.ts");
    // await runTsFile("./updateRanging.ts");
    // await runTsFile("./sendTelegram.ts");
  } catch (error) {
    console.error("Error in 4 PM scheduled job:", error);
  }
});
