const { getConfig } = require("./config");
const { runChecks } = require("./services/liveChecker");
const { loadEnv } = require("./utils/env");
const logger = require("./utils/logger");

loadEnv();

async function runOnce() {
  const config = getConfig();
  const summary = await runChecks(config);
  console.log(JSON.stringify(summary, null, 2));
  return summary;
}

async function monitor() {
  const config = getConfig();
  logger.info("Live checking monitor started", {
    intervalSeconds: config.intervalSeconds,
    dryRun: config.dryRun,
  });

  while (true) {
    try {
      await runChecks(getConfig());
    } catch (error) {
      logger.error("Live checking cycle failed", {
        error: error.message,
        stack: error.stack,
      });
    }

    await new Promise((resolve) => setTimeout(resolve, config.intervalSeconds * 1000));
  }
}

if (require.main === module) {
  const command = process.argv[2] || "once";
  const runner = command === "monitor" ? monitor : runOnce;

  runner().catch((error) => {
    logger.error("Live checking failed", {
      error: error.message,
      stack: error.stack,
    });
    process.exit(1);
  });
}
