import { readdir, unlink, stat } from 'fs/promises';
import { join } from 'path';
import { getLogsDir, fileExists } from './utils.js';
import { createLogger } from './logger.js';
const logger = createLogger('cleanup');
export async function cleanupOrphanedLogFiles(activeSessions, options = {}) {
    const { maxAgeDays = 7, skipSession } = options;
    let deletedCount = 0;
    const logsDir = getLogsDir();
    if (!(await fileExists(logsDir))) {
        return 0;
    }
    const files = await readdir(logsDir);
    const bridgeLogPattern = /^bridge-(@.+?)\.log(?:\.\d+)?$/;
    const cutoffTime = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
    logger.debug(`Cleaning orphaned logs older than ${maxAgeDays} days`);
    for (const file of files) {
        const match = file.match(bridgeLogPattern);
        if (!match || !match[1])
            continue;
        const sessionName = match[1];
        if (skipSession && sessionName === skipSession) {
            logger.debug(`Skipping current session's log file: ${file}`);
            continue;
        }
        if (!activeSessions[sessionName]) {
            const filePath = join(logsDir, file);
            try {
                const fileStats = await stat(filePath);
                const fileAge = fileStats.mtime.getTime();
                const ageInDays = Math.floor((Date.now() - fileAge) / (24 * 60 * 60 * 1000));
                if (fileAge < cutoffTime) {
                    await unlink(filePath);
                    deletedCount++;
                    logger.debug(`Removed orphaned log file: ${file} (age: ${ageInDays} days)`);
                }
                else {
                    logger.debug(`Keeping recent orphaned log file: ${file} (age: ${ageInDays} days)`);
                }
            }
            catch {
                logger.debug(`Failed to process log file: ${file}`);
            }
        }
    }
    return deletedCount;
}
//# sourceMappingURL=cleanup.js.map