import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
import { init_paths, resolveCronRunsDir } from "../config/paths.js";
import { appendFile, mkdir, readFile, readdir, unlink, writeFile } from "fs/promises";
import { join } from "path";
//#region src/cron/run-log-store.ts
init_paths();
init_logger();
const log = createLogger("CronRunLog");
const MAX_LINES_PER_FILE = 2e3;
const TRIM_TO_LINES = 1500;
var CronRunLogStore = class {
	dir;
	constructor(dir) {
		this.dir = dir ?? resolveCronRunsDir();
	}
	async ensureDir() {
		await mkdir(this.dir, { recursive: true });
	}
	jobFile(jobId) {
		return join(this.dir, `${jobId}.jsonl`);
	}
	async appendCompleted(execution) {
		if (execution.status === "running") return;
		try {
			await this.ensureDir();
			const line = `${JSON.stringify(execution)}\n`;
			await appendFile(this.jobFile(execution.jobId), line, "utf8");
			await this.maybeTrimFile(execution.jobId);
		} catch (err) {
			log.error({
				jobId: execution.jobId,
				err
			}, "Failed to persist cron run");
		}
	}
	async maybeTrimFile(jobId) {
		const file = this.jobFile(jobId);
		let content;
		try {
			content = await readFile(file, "utf8");
		} catch {
			return;
		}
		const lines = content.split("\n").filter((l) => l.trim().length > 0);
		if (lines.length <= MAX_LINES_PER_FILE) return;
		await writeFile(file, `${lines.slice(-TRIM_TO_LINES).join("\n")}\n`, "utf8");
	}
	async readJobHistory(jobId, limit) {
		if (limit <= 0) return [];
		let content;
		try {
			content = await readFile(this.jobFile(jobId), "utf8");
		} catch {
			return [];
		}
		const lines = content.split("\n").filter((l) => l.trim().length > 0);
		const parsed = [];
		for (const line of lines) try {
			parsed.push(JSON.parse(line));
		} catch {}
		parsed.sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime());
		return parsed.slice(0, limit);
	}
	/**
	* Latest runs across all jobs (disk only). Caller supplies job names for display.
	*/
	async readAllRuns(limit, jobNames) {
		if (limit <= 0) return [];
		let names;
		try {
			await this.ensureDir();
			names = await readdir(this.dir);
		} catch {
			return [];
		}
		const rows = [];
		for (const fname of names) {
			if (!fname.endsWith(".jsonl")) continue;
			const jobId = fname.slice(0, -6);
			let content;
			try {
				content = await readFile(join(this.dir, fname), "utf8");
			} catch {
				continue;
			}
			const lines = content.split("\n").filter((l) => l.trim().length > 0);
			for (const line of lines) try {
				const e = JSON.parse(line);
				rows.push({
					...e,
					jobName: jobNames.get(jobId) ?? jobNames.get(e.jobId)
				});
			} catch {}
		}
		rows.sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime());
		return rows.slice(0, limit);
	}
	async deleteJobRuns(jobId) {
		try {
			await unlink(this.jobFile(jobId));
		} catch {}
	}
};
//#endregion
export { CronRunLogStore };

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