import { createWriteStream } from 'fs';
import { stat, readdir, unlink, rename } from 'fs/promises';
import { join, dirname } from 'path';
import { ensureDir } from './utils.js';
export class FileLogger {
    filePath;
    maxSize;
    maxFiles;
    stream = null;
    writtenBytes = 0;
    constructor(options) {
        this.filePath = options.filePath;
        this.maxSize = options.maxSize ?? 10 * 1024 * 1024;
        this.maxFiles = options.maxFiles ?? 5;
    }
    async init() {
        const dir = dirname(this.filePath);
        await ensureDir(dir);
        try {
            const stats = await stat(this.filePath);
            this.writtenBytes = stats.size;
            if (this.writtenBytes >= this.maxSize) {
                await this.rotate();
                this.writtenBytes = 0;
            }
        }
        catch {
            this.writtenBytes = 0;
        }
        this.stream = createWriteStream(this.filePath, { flags: 'a' });
        this.stream.on('error', (error) => {
            console.error('[file-logger] Stream error:', error);
        });
    }
    write(message) {
        if (!this.stream) {
            console.error('[file-logger] Logger not initialized');
            return;
        }
        const line = message.endsWith('\n') ? message : `${message}\n`;
        const bytes = Buffer.byteLength(line, 'utf8');
        this.stream.write(line);
        this.writtenBytes += bytes;
        if (this.writtenBytes >= this.maxSize) {
            void this.rotateAsync();
        }
    }
    async rotateAsync() {
        try {
            await this.rotate();
            this.writtenBytes = 0;
        }
        catch (error) {
            console.error('[file-logger] Rotation error:', error);
        }
    }
    async rotate() {
        if (this.stream) {
            this.stream.end();
            this.stream = null;
        }
        const dir = dirname(this.filePath);
        const basename = this.filePath;
        const rotatedFiles = [];
        try {
            const files = await readdir(dir);
            for (const file of files) {
                const fullPath = join(dir, file);
                if (fullPath.startsWith(basename + '.')) {
                    const numStr = fullPath.substring(basename.length + 1);
                    const num = parseInt(numStr, 10);
                    if (!isNaN(num)) {
                        rotatedFiles.push({ path: fullPath, num });
                    }
                }
            }
        }
        catch {
        }
        rotatedFiles.sort((a, b) => b.num - a.num);
        for (const file of rotatedFiles) {
            if (file.num >= this.maxFiles) {
                try {
                    await unlink(file.path);
                }
                catch {
                }
            }
        }
        for (const file of rotatedFiles) {
            if (file.num < this.maxFiles) {
                const newPath = `${basename}.${file.num + 1}`;
                try {
                    await rename(file.path, newPath);
                }
                catch {
                }
            }
        }
        try {
            await rename(basename, `${basename}.1`);
        }
        catch {
        }
        this.stream = createWriteStream(this.filePath, { flags: 'a' });
        this.stream.on('error', (error) => {
            console.error('[file-logger] Stream error:', error);
        });
    }
    async close() {
        if (this.stream) {
            return new Promise((resolve) => {
                if (this.stream) {
                    this.stream.end(() => {
                        resolve();
                    });
                    this.stream = null;
                }
                else {
                    resolve();
                }
            });
        }
    }
}
//# sourceMappingURL=file-logger.js.map