import type { Adapter } from "./adapter";
import { AdapterResultSchema } from "./schema";
import { CollectorState } from "./state";
import { PollScheduler, type Clock } from "./scheduler";
import { Journal } from "./journal";
import { journalFile } from "./paths";

/** Wires a set of adapters to a CollectorState via a PollScheduler. Adapter poll errors are absorbed. */
export function buildScheduler(
  adapters: readonly Adapter[],
  state: CollectorState,
  clock?: Clock,
  rng?: () => number,
): PollScheduler {
  for (const adapter of adapters) {
    state.registerAdapter(adapter.id, adapter.interval);
  }

  return new PollScheduler(
    adapters,
    (adapter, outcome, atTs, durationMs) => {
      if (outcome.ok) {
        const validated = AdapterResultSchema.parse(outcome.data);
        state.recordSuccess(
          adapter.id,
          atTs,
          validated.items,
          validated.panels,
          durationMs,
          validated.completeScopes,
        );
      } else {
        state.recordFailure(adapter.id, atTs, outcome.error, durationMs);
      }
    },
    clock,
    rng,
  );
}

export function buildState(now?: () => number): CollectorState {
  const journal = new Journal(journalFile());
  return new CollectorState(journal, now);
}
