import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
import { resolveWorkflowRunEventsPath, resolveWorkflowRunsDir } from "./paths.js";
import { randomUUID } from "node:crypto";
import { appendFile, mkdir, readFile, readdir } from "node:fs/promises";
import { dirname } from "node:path";
//#region src/workflows/store/event-store.ts
init_logger();
const log = createLogger("WorkflowEventStore");
var WorkflowEventStore = class {
	constructor(config, agentId) {
		this.config = config;
		this.agentId = agentId;
	}
	async append(input) {
		const eventsPath = resolveWorkflowRunEventsPath(this.config, this.agentId, input.runId);
		await mkdir(dirname(eventsPath), { recursive: true });
		const previousEvents = await this.readRunEvents(input.runId);
		const event = {
			id: randomUUID(),
			runId: input.runId,
			sequence: previousEvents.length + 1,
			type: input.type,
			payload: input.payload,
			createdAtMs: input.createdAtMs ?? Date.now()
		};
		await appendFile(eventsPath, `${JSON.stringify(event)}\n`, "utf8");
		return event;
	}
	async readRunEvents(runId) {
		const eventsPath = resolveWorkflowRunEventsPath(this.config, this.agentId, runId);
		let content;
		try {
			content = await readFile(eventsPath, "utf8");
		} catch (err) {
			if ((err && typeof err === "object" && "code" in err ? String(err.code) : "") === "ENOENT") return [];
			log.warn({
				err,
				runId,
				eventsPath
			}, "Workflow events read failed");
			return [];
		}
		const events = [];
		for (const line of content.split("\n")) {
			if (!line.trim()) continue;
			try {
				const event = JSON.parse(line);
				if (event.runId === runId && Number.isFinite(event.sequence)) events.push(event);
			} catch (err) {
				log.warn({
					err,
					runId,
					linePreview: line.slice(0, 160)
				}, "Workflow event line parse failed");
			}
		}
		events.sort((left, right) => left.sequence - right.sequence);
		return events;
	}
	async listRunIds() {
		const runsDir = resolveWorkflowRunsDir(this.config, this.agentId);
		let entries;
		try {
			entries = await readdir(runsDir);
		} catch (err) {
			if ((err && typeof err === "object" && "code" in err ? String(err.code) : "") === "ENOENT") return [];
			log.warn({
				err,
				runsDir
			}, "Workflow runs directory read failed");
			return [];
		}
		return entries.filter((entry) => !entry.startsWith(".") && !entry.includes("/") && !entry.includes("\\"));
	}
};
function createWorkflowEventStore(config, agentId) {
	return new WorkflowEventStore(config, agentId);
}
//#endregion
export { WorkflowEventStore, createWorkflowEventStore };

//# sourceMappingURL=event-store.js.map