"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveStructuredLogFilePath = resolveStructuredLogFilePath;
exports.createStructuredLogEmitter = createStructuredLogEmitter;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
function normalizeStructuredLogDir(env = process.env) {
    const value = env['PLAYDROP_STRUCTURED_LOG_DIR'];
    if (typeof value !== 'string') {
        return null;
    }
    const normalized = value.trim();
    return normalized.length > 0 ? normalized : null;
}
function resolveStructuredLogFilePath(service, env = process.env) {
    const directory = normalizeStructuredLogDir(env);
    if (!directory) {
        return null;
    }
    return path_1.default.join(directory, `${service}.jsonl`);
}
function createStructuredLogEmitter(service, env = process.env) {
    const logFilePath = resolveStructuredLogFilePath(service, env);
    const fileStream = logFilePath
        ? fs_1.default.createWriteStream(logFilePath, { flags: 'a' })
        : null;
    return (payload, stream = 'stdout') => {
        const normalizedPayload = Object.prototype.hasOwnProperty.call(payload, 'timestamp')
            ? payload
            : {
                timestamp: new Date().toISOString(),
                ...payload,
            };
        const line = `${JSON.stringify(normalizedPayload)}\n`;
        if (stream === 'stderr') {
            process.stderr.write(line);
        }
        else {
            process.stdout.write(line);
        }
        fileStream?.write(line);
    };
}
