import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
//#region src/channels/heartbeat-scheduler.ts
init_logger();
const log = createLogger("ChannelHeartbeatScheduler");
/** Minimum gap between successive soft-restart attempts for the same channel. */
const HEARTBEAT_RESTART_THROTTLE_MS = 6e4;
var ChannelHeartbeatScheduler = class {
	opts;
	/** Key shape: `${pluginId}:${accountId}`. */
	timers = /* @__PURE__ */ new Map();
	lastRestartAt = /* @__PURE__ */ new Map();
	constructor(opts) {
		this.opts = opts;
	}
	/** Register heartbeat checks for every account exposed by the plugin. */
	schedule(plugin) {
		const hb = plugin.heartbeat;
		if (!hb) return;
		this.clear(plugin.id);
		let accountIds;
		try {
			accountIds = plugin.config.listAccountIds(this.opts.getConfig());
		} catch (err) {
			log.warn({
				channel: plugin.id,
				err
			}, "Heartbeat: failed to list accounts");
			return;
		}
		for (const accountId of accountIds) {
			const key = `${plugin.id}:${accountId}`;
			const timer = setInterval(() => void this.runProbe(plugin, accountId), hb.intervalMs);
			this.timers.set(key, timer);
		}
	}
	/** Drop every probe scheduled for `pluginId` (called on stop / soft-restart). */
	clear(pluginId) {
		const prefix = `${pluginId}:`;
		for (const key of [...this.timers.keys()]) {
			if (!key.startsWith(prefix)) continue;
			clearInterval(this.timers.get(key));
			this.timers.delete(key);
		}
	}
	/** Test helper / process shutdown. */
	clearAll() {
		for (const timer of this.timers.values()) clearInterval(timer);
		this.timers.clear();
		this.lastRestartAt.clear();
	}
	async runProbe(plugin, accountId) {
		const hb = plugin.heartbeat;
		if (!hb) return;
		const cfg = this.opts.getConfig();
		try {
			const r = await hb.check({
				cfg,
				accountId
			});
			this.opts.healthMonitor.set(plugin.id, accountId, {
				healthy: r.healthy,
				lastCheckAt: Date.now(),
				detail: typeof r.details === "string" ? r.details : r.details != null ? JSON.stringify(r.details) : void 0
			});
			if (!r.healthy) {
				log.warn({
					channel: plugin.id,
					accountId,
					detail: r.details
				}, "Channel heartbeat unhealthy");
				const now = Date.now();
				if (now - (this.lastRestartAt.get(plugin.id) ?? 0) < HEARTBEAT_RESTART_THROTTLE_MS) return;
				this.lastRestartAt.set(plugin.id, now);
				this.opts.requestSoftRestart(plugin.id);
			}
		} catch (err) {
			this.opts.healthMonitor.set(plugin.id, accountId, {
				healthy: false,
				lastCheckAt: Date.now(),
				detail: err instanceof Error ? err.message : String(err)
			});
			log.error({
				channel: plugin.id,
				accountId,
				err
			}, "Channel heartbeat check failed");
		}
	}
};
//#endregion
export { ChannelHeartbeatScheduler };

//# sourceMappingURL=heartbeat-scheduler.js.map