import { __esmMin } from "../../../_virtual/_rolldown/runtime.js";
import { config, getLogDir, init_config } from "./config.js";
import { writeFile } from "fs/promises";
import { join } from "path";
import { readFileSync, readdirSync, statSync, unlinkSync } from "fs";
import { gzip } from "zlib";
import { promisify } from "util";
//#region src/utils/logger/rotation.ts
/**
* Log Rotation
* Automatic log rotation based on size and retention policy
*/
/**
* Get compressed log path
*/
function getCompressedLogPath(originalPath) {
	return `${originalPath}.gz`;
}
/**
* Rotate logs if they exceed max size
*/
async function rotateLogs() {
	const result = {
		rotated: 0,
		deleted: 0,
		compressed: 0,
		errors: []
	};
	try {
		const files = readdirSync(getLogDir());
		const maxSizeBytes = config.maxFileSizeMB * 1024 * 1024;
		for (const file of files) {
			if (!file.endsWith(".log") || file.endsWith(".gz")) continue;
			const filePath = join(getLogDir(), file);
			if (statSync(filePath).size >= maxSizeBytes) {
				const compressedPath = getCompressedLogPath(filePath);
				try {
					await writeFile(compressedPath, await compressAsync(readFileSync(filePath)));
					unlinkSync(filePath);
					result.compressed++;
					result.rotated++;
				} catch (err) {
					result.errors.push(`Failed to compress ${file}: ${err}`);
				}
			}
		}
	} catch (err) {
		result.errors.push(`Rotation failed: ${err}`);
	}
	return result;
}
/**
* Clean old logs based on retention policy
*/
function cleanOldLogs(keepDays = config.retentionDays) {
	const result = {
		rotated: 0,
		deleted: 0,
		compressed: 0,
		errors: []
	};
	try {
		const cutoff = /* @__PURE__ */ new Date();
		cutoff.setDate(cutoff.getDate() - keepDays);
		const files = readdirSync(getLogDir());
		for (const file of files) {
			if (!file.endsWith(".log") && !file.endsWith(".log.gz")) continue;
			const filePath = join(getLogDir(), file);
			const stats = statSync(filePath);
			if (new Date(stats.mtime) < cutoff) try {
				unlinkSync(filePath);
				result.deleted++;
			} catch (err) {
				result.errors.push(`Failed to delete ${file}: ${err}`);
			}
		}
	} catch (err) {
		result.errors.push(`Cleanup failed: ${err}`);
	}
	return result;
}
var compressAsync;
var init_rotation = __esmMin((() => {
	init_config();
	compressAsync = promisify(gzip);
}));
//#endregion
init_rotation();
export { cleanOldLogs, init_rotation, rotateLogs };

//# sourceMappingURL=rotation.js.map