import { init_write_file_atomic, writeTextAtomic } from "../../infra/write-file-atomic.js";
import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
import { projectWorkflowRunView } from "../engine/projector.js";
import { resolveWorkflowRunViewPath } from "./paths.js";
import { WorkflowEventStore } from "./event-store.js";
import { readFile } from "node:fs/promises";
//#region src/workflows/store/run-store.ts
init_write_file_atomic();
init_logger();
const log = createLogger("WorkflowRunStore");
var WorkflowRunStore = class {
	eventStore;
	constructor(config, agentId, eventStore) {
		this.config = config;
		this.agentId = agentId;
		this.eventStore = eventStore ?? new WorkflowEventStore(config, agentId);
	}
	async rebuildRunView(runId) {
		const view = projectWorkflowRunView(await this.eventStore.readRunEvents(runId));
		if (!view) return null;
		await writeTextAtomic(resolveWorkflowRunViewPath(this.config, this.agentId, runId), `${JSON.stringify(view, null, 2)}\n`);
		return view;
	}
	async readRunView(runId) {
		const viewPath = resolveWorkflowRunViewPath(this.config, this.agentId, runId);
		try {
			const content = await readFile(viewPath, "utf8");
			return JSON.parse(content);
		} catch (err) {
			if ((err && typeof err === "object" && "code" in err ? String(err.code) : "") !== "ENOENT") log.debug({
				err,
				runId,
				viewPath
			}, "Workflow run view read failed; rebuilding from events");
			return this.rebuildRunView(runId);
		}
	}
	async listRunSummaries(limit = 50) {
		const safeLimit = Math.min(500, Math.max(1, Math.floor(limit)));
		const runIds = await this.eventStore.listRunIds();
		const summaries = [];
		for (const runId of runIds) {
			const view = await this.readRunView(runId);
			if (!view) continue;
			summaries.push({
				id: view.run.id,
				definitionId: view.run.definitionId,
				title: view.run.title,
				status: view.run.status,
				source: view.run.source,
				createdAtMs: view.run.createdAtMs,
				startedAtMs: view.run.startedAtMs,
				completedAtMs: view.run.completedAtMs,
				metrics: view.run.metrics
			});
		}
		summaries.sort((left, right) => right.createdAtMs - left.createdAtMs);
		return summaries.slice(0, safeLimit);
	}
};
function createWorkflowRunStore(config, agentId) {
	return new WorkflowRunStore(config, agentId);
}
//#endregion
export { WorkflowRunStore, createWorkflowRunStore };

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