import { formatBytes } from "../tty/format.js";
import { startOscProgress } from "../tty/osc-progress.js";
import { startSpinner } from "../tty/spinner.js";
import { createThemeRenderer, resolveThemeNameFromSources, resolveTrueColor, } from "../tty/theme.js";
function isRemoteSource(source) {
    try {
        const protocol = new URL(source).protocol;
        return protocol === "http:" || protocol === "https:";
    }
    catch {
        return false;
    }
}
export function createCliInputProgress(options) {
    const theme = createThemeRenderer({
        themeName: resolveThemeNameFromSources({
            env: options.envForRun.SUMMARIZE_THEME,
        }),
        enabled: options.enabled,
        trueColor: resolveTrueColor(options.envForRun),
    });
    let current = null;
    let modelId = null;
    let spinner = null;
    let stopOscProgress = null;
    let stopped = false;
    const modelSuffix = () => modelId ? `${theme.dim(" (model: ")}${theme.accent(modelId)}${theme.dim(")")}` : "";
    const sizeLabel = () => typeof current?.sizeBytes === "number" ? formatBytes(current.sizeBytes) : null;
    const metadata = ({ includeMediaType }) => {
        if (!current)
            return "";
        const details = [includeMediaType ? current.mediaType : null, sizeLabel()].filter((value) => Boolean(value));
        const name = current.filename;
        const base = name && details.length > 0
            ? `${name} ${theme.dim("(")}${details.join(", ")}${theme.dim(")")}`
            : name || details.join(", ");
        return `${base}${modelSuffix()}`;
    };
    const render = () => {
        if (!current)
            return "";
        if (current.phase === "loading") {
            const label = isRemoteSource(current.source) ? "Downloading file" : "Loading file";
            const size = sizeLabel();
            return `${theme.label(label)}${theme.dim(size ? ` (${size})…` : "…")}`;
        }
        const label = current.phase === "transcribing"
            ? "Transcribing"
            : current.phase === "extracting"
                ? "Extracting text"
                : "Summarizing";
        const meta = metadata({ includeMediaType: current.phase !== "transcribing" });
        return meta
            ? `${theme.label(label)} ${meta}${theme.dim("…")}`
            : `${theme.label(label)}${theme.dim("…")}`;
    };
    const oscLabel = (event) => {
        if (event.phase === "loading") {
            return isRemoteSource(event.source) ? "Downloading file" : "Loading file";
        }
        if (event.phase === "transcribing")
            return "Transcribing media";
        if (event.phase === "extracting")
            return "Extracting text";
        return "Summarizing";
    };
    const pauseProgressLine = () => {
        spinner?.pause();
        return () => spinner?.resume();
    };
    const ensureStarted = (event) => {
        if (spinner || stopped)
            return;
        stopOscProgress = startOscProgress({
            label: oscLabel(event),
            indeterminate: true,
            env: options.env,
            isTty: options.enabled,
            write: (data) => options.stderr.write(data),
        });
        spinner = startSpinner({
            text: render(),
            enabled: options.enabled,
            stream: options.stderr,
            color: theme.palette.spinner,
        });
        options.progressGate.setClearProgressBeforeStdout(pauseProgressLine);
    };
    return {
        handleEvent: (event) => {
            if (stopped)
                return;
            if (event.type === "input-progress") {
                current = event;
                ensureStarted(event);
                spinner?.setText(render());
                return;
            }
            if (event.type === "model-selected" && spinner) {
                modelId = event.modelId;
                spinner.setText(render());
            }
        },
        stop: () => {
            if (stopped)
                return;
            stopped = true;
            options.progressGate.clearProgressIfCurrent(pauseProgressLine);
            spinner?.stopAndClear();
            stopOscProgress?.();
        },
    };
}
//# sourceMappingURL=cli-input-progress.js.map