function isPerfTraceEnabled(env) {
    const value = env.SUMMARIZE_PERF_TRACE?.trim().toLowerCase();
    return value === "1" || value === "true" || value === "yes";
}
function formatMs(value) {
    return `${value.toFixed(value < 10 ? 1 : 0)}ms`;
}
export function createPerfTrace({ env, stderr, }) {
    if (!isPerfTraceEnabled(env))
        return null;
    const startedAt = performance.now();
    const events = [];
    let firstStdout = false;
    let finished = false;
    const mark = (name, detail) => {
        events.push({
            name,
            elapsedMs: performance.now() - startedAt,
            detail: detail?.trim() || null,
        });
    };
    mark("cli:start");
    return {
        mark,
        wrapStdout(stdout) {
            const wrapped = Object.create(stdout);
            wrapped.write = ((chunk, ...args) => {
                if (!firstStdout) {
                    firstStdout = true;
                    const bytes = typeof chunk === "string"
                        ? Buffer.byteLength(chunk)
                        : Buffer.isBuffer(chunk)
                            ? chunk.byteLength
                            : null;
                    mark("stdout:first-write", bytes == null ? null : `bytes=${bytes.toString()}`);
                }
                return stdout.write.call(stdout, chunk, ...args);
            });
            return wrapped;
        },
        finish(detail) {
            if (finished)
                return;
            finished = true;
            mark("cli:finish", detail ?? null);
            stderr.write("[summarize:perf]\n");
            for (const event of events) {
                const suffix = event.detail ? ` ${event.detail}` : "";
                stderr.write(`  ${formatMs(event.elapsedMs)} ${event.name}${suffix}\n`);
            }
        },
    };
}
//# sourceMappingURL=perf-trace.js.map