"use strict";
// =============================================================================
// Pure Agent - Logger
// Ported from Hermes hermes_logging.py
// =============================================================================
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.PureAgentLogger = exports.LogLevel = void 0;
exports.getLogger = getLogger;
exports.resetLogger = resetLogger;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const constants_1 = require("./constants");
// ---------------------------------------------------------------------------
// Log levels
// ---------------------------------------------------------------------------
var LogLevel;
(function (LogLevel) {
    LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
    LogLevel[LogLevel["INFO"] = 1] = "INFO";
    LogLevel[LogLevel["WARN"] = 2] = "WARN";
    LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
})(LogLevel || (exports.LogLevel = LogLevel = {}));
const LOG_LEVEL_NAMES = {
    [LogLevel.DEBUG]: 'DEBUG',
    [LogLevel.INFO]: 'INFO',
    [LogLevel.WARN]: 'WARN',
    [LogLevel.ERROR]: 'ERROR',
};
// ---------------------------------------------------------------------------
// Rotating file writer
// ---------------------------------------------------------------------------
class RotatingFileWriter {
    filePath;
    maxSize;
    maxBackups;
    stream = null;
    currentSize = 0;
    constructor(filePath, maxSizeMB = 50, maxBackups = 3) {
        this.filePath = filePath;
        this.maxSize = maxSizeMB * 1024 * 1024;
        this.maxBackups = maxBackups;
        this._open();
    }
    _open() {
        const dir = path.dirname(this.filePath);
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
        try {
            const stat = fs.statSync(this.filePath);
            this.currentSize = stat.size;
        }
        catch {
            this.currentSize = 0;
        }
        this.stream = fs.createWriteStream(this.filePath, { flags: 'a' });
    }
    write(data) {
        if (!this.stream)
            return;
        const buf = Buffer.from(data, 'utf-8');
        this.currentSize += buf.length;
        if (this.currentSize >= this.maxSize) {
            this._rotate();
        }
        this.stream.write(buf);
    }
    _rotate() {
        if (this.stream) {
            this.stream.end();
            this.stream = null;
        }
        // Shift backup files
        for (let i = this.maxBackups - 1; i >= 1; i--) {
            const src = `${this.filePath}.${i}`;
            const dst = `${this.filePath}.${i + 1}`;
            if (fs.existsSync(src)) {
                try {
                    fs.renameSync(src, dst);
                }
                catch { /* ignore */ }
            }
        }
        // Current -> .1
        if (fs.existsSync(this.filePath)) {
            try {
                fs.renameSync(this.filePath, `${this.filePath}.1`);
            }
            catch { /* ignore */ }
        }
        this.currentSize = 0;
        this._open();
    }
    close() {
        if (this.stream) {
            this.stream.end();
            this.stream = null;
        }
    }
}
// ---------------------------------------------------------------------------
// Logger class
// ---------------------------------------------------------------------------
class PureAgentLogger {
    agentWriter;
    errorWriter;
    minLevel;
    sessionId = null;
    constructor(minLevel = LogLevel.INFO) {
        (0, constants_1.ensureDirectories)();
        this.minLevel = minLevel;
        this.agentWriter = new RotatingFileWriter((0, constants_1.getAgentLogPath)(), 50, 3);
        this.errorWriter = new RotatingFileWriter((0, constants_1.getErrorLogPath)(), 20, 5);
    }
    setSessionId(sessionId) {
        this.sessionId = sessionId;
    }
    clearSessionId() {
        this.sessionId = null;
    }
    debug(message, ...args) {
        this._log(LogLevel.DEBUG, message, args);
    }
    info(message, ...args) {
        this._log(LogLevel.INFO, message, args);
    }
    log(message, ...args) {
        this._log(LogLevel.INFO, message, args);
    }
    warn(message, ...args) {
        this._log(LogLevel.WARN, message, args);
    }
    error(message, ...args) {
        this._log(LogLevel.ERROR, message, args);
    }
    _log(level, message, args) {
        if (level < this.minLevel)
            return;
        const timestamp = new Date().toISOString();
        const levelName = LOG_LEVEL_NAMES[level];
        const sessionTag = this.sessionId ? ` [${this.sessionId.slice(0, 8)}]` : '';
        const formatted = args.length > 0
            ? `${message} ${args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ')}`
            : message;
        const line = `${timestamp} ${levelName}${sessionTag} ${formatted}\n`;
        this.agentWriter.write(line);
        if (level >= LogLevel.WARN) {
            this.errorWriter.write(line);
        }
    }
    close() {
        this.agentWriter.close();
        this.errorWriter.close();
    }
}
exports.PureAgentLogger = PureAgentLogger;
// ---------------------------------------------------------------------------
// Singleton instance
// ---------------------------------------------------------------------------
let _instance = null;
function getLogger() {
    if (!_instance) {
        _instance = new PureAgentLogger();
    }
    return _instance;
}
function resetLogger() {
    if (_instance) {
        _instance.close();
        _instance = null;
    }
}
//# sourceMappingURL=logger.js.map