import { createMarkdownStreamer, render as renderMarkdownAnsi } from "markdansi";
import { prepareMarkdownForTerminalStreaming } from "./markdown.js";
import { createStreamOutputGate } from "./stream-output.js";
import { isRichTty, markdownRenderWidth, supportsColor } from "./terminal.js";
export function createTerminalSummaryStream({ stdout, env, envForRun, plain, outputMode, clearProgressForStdout, restoreProgressAfterStdout, }) {
    const richTty = isRichTty(stdout);
    const shouldRenderMarkdown = !plain && richTty;
    const resolvedOutputMode = outputMode ?? (richTty ? "delta" : "line");
    const outputGate = shouldRenderMarkdown
        ? null
        : createStreamOutputGate({
            stdout,
            clearProgressForStdout,
            restoreProgressAfterStdout: resolvedOutputMode === "delta" ? null : (restoreProgressAfterStdout ?? null),
            outputMode: resolvedOutputMode,
            richTty: richTty && resolvedOutputMode === "line",
            rewriteOnReplacement: richTty && resolvedOutputMode === "delta",
            restoreDuringStream: resolvedOutputMode !== "delta",
        });
    const createStreamer = () => shouldRenderMarkdown
        ? createMarkdownStreamer({
            render: (markdown) => renderMarkdownAnsi(prepareMarkdownForTerminalStreaming(markdown), {
                width: markdownRenderWidth(stdout, env),
                wrap: true,
                color: supportsColor(stdout, envForRun),
                hyperlinks: true,
            }),
            spacing: "single",
        })
        : null;
    let streamer = createStreamer();
    let wroteLeadingBlankLine = false;
    const writeRendered = (text) => {
        if (!text)
            return false;
        clearProgressForStdout();
        if (!wroteLeadingBlankLine) {
            stdout.write(`\n${text.replace(/^\n+/, "")}`);
            wroteLeadingBlankLine = true;
        }
        else {
            stdout.write(text);
        }
        restoreProgressAfterStdout?.();
        return true;
    };
    return {
        onChunk: ({ streamed, prevStreamed, appended }) => {
            if (outputGate) {
                return outputGate.handleChunk(streamed, prevStreamed);
            }
            return writeRendered(streamer?.push(appended) ?? "");
        },
        onDone: (finalText) => {
            if (outputGate) {
                const emitted = outputGate.finalize(finalText);
                if (resolvedOutputMode === "delta")
                    restoreProgressAfterStdout?.();
                return emitted;
            }
            return writeRendered(streamer?.finish() ?? "");
        },
        onReset: () => {
            outputGate?.reset();
            streamer = createStreamer();
            wroteLeadingBlankLine = false;
        },
    };
}
//# sourceMappingURL=summary-stream.js.map