#!/usr/bin/env node
import { o as logger_default } from "./logger-BHK-IvoX.js";
import { _ as getDbSignalPath } from "./tables-Bgd8sdal.js";
import fs from "fs";
import debounce from "debounce";

//#region src/database/signal.ts
/**
* Updates the signal file with the current timestamp and optional eval ID.
* This is used to notify clients that there are new data available.
* @param evalId - Optional eval ID that triggered the update
*/
function updateSignalFile(evalId) {
	const filePath = getDbSignalPath();
	try {
		const now = /* @__PURE__ */ new Date();
		const content = evalId ? `${evalId}:${now.toISOString()}` : now.toISOString();
		fs.writeFileSync(filePath, content);
	} catch (err) {
		logger_default.warn(`Failed to write database signal file: ${err}`);
	}
}
/**
* Reads the signal file and returns the eval ID if present.
* @returns The eval ID from the signal file, or undefined if not present
*/
function readSignalEvalId() {
	const filePath = getDbSignalPath();
	try {
		const content = fs.readFileSync(filePath, "utf8").trim();
		if (/^\d{4}-\d{2}-\d{2}T/.test(content)) return;
		if (content.includes(":")) {
			const evalId = content.split(":")[0];
			if (evalId && evalId.length > 8) return evalId;
		}
		return;
	} catch {
		return;
	}
}
/**
* Ensures the signal file exists, creating it if necessary.
*/
function ensureSignalFile() {
	const filePath = getDbSignalPath();
	if (!fs.existsSync(filePath)) {
		logger_default.debug(`Creating signal file at ${filePath}`);
		fs.writeFileSync(filePath, (/* @__PURE__ */ new Date()).toISOString());
	}
}
/**
* Sets up a watcher on the signal file and calls the callback when it changes.
* @param onChange - Callback function that is called when the signal file changes
* @returns The watcher instance
*/
function setupSignalWatcher(onChange) {
	const filePath = getDbSignalPath();
	logger_default.debug(`Setting up file watcher on ${filePath}`);
	ensureSignalFile();
	try {
		const watcher = fs.watch(filePath);
		watcher.on("change", debounce(onChange, 250));
		watcher.on("error", (error) => {
			logger_default.warn(`File watcher error: ${error}`);
		});
		return watcher;
	} catch (error) {
		logger_default.warn(`Failed to set up file watcher: ${error}`);
		throw error;
	}
}

//#endregion
export { setupSignalWatcher as n, updateSignalFile as r, readSignalEvalId as t };
//# sourceMappingURL=signal-CBgKJYME.js.map