import { QbitClient } from "../qbit/qbit.client"
import { tickLoopJobs } from "./loop.engine"
import { getStatusSnapshot, refreshJobsStatus, setQbitStatus, setTorrentsStatus } from "../status/status.service"
import { emitQbitHealth, emitStatusUpdate, emitWatcherItems } from "../realtime/emitter"
import { logger } from "../utils/logger"
import { getWatcherItems } from "../watcher/watcher.service"

export const startLoopScheduler = (qbit: QbitClient, intervalMs: number) => {
  setInterval(async () => {
    try {
      const torrents = await qbit.getTorrentsInfo();
      const transfer = await qbit.getTransferInfo();
      setTorrentsStatus(torrents, transfer);
      await tickLoopJobs(qbit, torrents);
      const jobs = await refreshJobsStatus();
      const current = await getStatusSnapshot();
      emitStatusUpdate({
        qbit: { ...current.qbit, ok: true },
        torrents,
        transfer,
        jobs,
      });
      emitWatcherItems(await getWatcherItems());
    } catch (error) {
      const message = error instanceof Error ? error.message : "Unknown error";
      logger.error({ error }, "Loop scheduler tick failed");
      setQbitStatus({ ok: false, lastError: message });
      emitQbitHealth({ ok: false, lastError: message });
      try {
        const current = await getStatusSnapshot();
        emitStatusUpdate({
          ...current,
          qbit: { ...current.qbit, ok: false, lastError: message },
        });
      } catch {
        // Swallow secondary status errors to keep scheduler alive.
      }
    }
  }, intervalMs);
};
