import { logger } from "../utils/logger.js";
/**
 * Middleware that logs token usage and costs for every successful request.
 */
export class UsageLoggerMiddleware {
    options;
    name = "UsageLogger";
    constructor(options = {}) {
        this.options = options;
    }
    async onResponse(ctx, result) {
        const usage = result.usage;
        if (!usage)
            return;
        const logFn = this.options.logger || ((msg, data) => logger.info(`${msg} ${JSON.stringify(data)}`));
        const prefix = this.options.prefix ? `[${this.options.prefix}] ` : "";
        const message = `${prefix}LLM Usage: ${ctx.provider}/${ctx.model}`;
        const data = {
            requestId: ctx.requestId,
            tokens: {
                input: usage.input_tokens,
                output: usage.output_tokens,
                total: usage.total_tokens,
                cached: usage.cached_tokens
            },
            cost: usage.cost ? usage.cost.toFixed(6) : undefined
        };
        logFn(message, data);
    }
}
/**
 * Factory function for creating the usage logger middleware.
 */
export function UsageLogger(options = {}) {
    return new UsageLoggerMiddleware(options);
}
