import { collectAllHosts } from "./collectors/hosts.js";
import { collectAllServices } from "./collectors/services.js";
import { collectAllNetwork } from "./collectors/network.js";
import { collectAllSites, discoverSites } from "./collectors/sites.js";
import { runEvaluator } from "./alerting/evaluator.js";

const INTERVALS = {
  hosts: 60_000,
  services: 60_000,
  network: 30_000,
  sites: 120_000,
  siteDiscovery: 600_000,
};

const timers: ReturnType<typeof setInterval>[] = [];

async function collectAndEvaluate(collectors: (() => Promise<void>)[]): Promise<void> {
  await Promise.allSettled(collectors.map((c) => c()));
  runEvaluator().catch((e) => console.error("[scheduler] Evaluator error:", e));
}

export async function startScheduler(): Promise<void> {
  console.log("Status scheduler starting...");

  await Promise.allSettled([
    discoverSites().then(() => collectAllSites()),
    collectAllHosts(),
    collectAllServices(),
    collectAllNetwork(),
  ]);

  console.log("Initial status collection complete");
  runEvaluator().catch((e) => console.error("[scheduler] Initial evaluator error:", e));

  timers.push(setInterval(() => {
    collectAndEvaluate([collectAllHosts]).catch(console.error);
  }, INTERVALS.hosts));

  timers.push(setInterval(() => {
    collectAndEvaluate([collectAllServices]).catch(console.error);
  }, INTERVALS.services));

  timers.push(setInterval(() => {
    collectAndEvaluate([collectAllNetwork]).catch(console.error);
  }, INTERVALS.network));

  timers.push(setInterval(() => {
    collectAndEvaluate([collectAllSites]).catch(console.error);
  }, INTERVALS.sites));

  timers.push(setInterval(() => { discoverSites().catch(console.error); }, INTERVALS.siteDiscovery));

  console.log("Status scheduler running");
}

export function stopScheduler(): void {
  for (const t of timers) clearInterval(t);
  timers.length = 0;
}
