import { createOscProgressController } from "../../../tty/osc-progress.js";
import { startSpinner } from "../../../tty/spinner.js";
import { createWebsiteProgress } from "../../../tty/website-progress.js";
import { createUrlProgressStatus } from "./progress-status.js";
import { composeUrlFlowHooks } from "./types.js";
function isMissingSlidesDependencyError(message) {
    const lower = message.toLowerCase();
    return (lower.includes("missing ffmpeg") ||
        lower.includes("install ffmpeg") ||
        lower.includes("require yt-dlp") ||
        lower.includes("install yt-dlp") ||
        lower.includes("missing tesseract"));
}
export function writeSlidesBackgroundFailureWarning({ ctx, theme, message, }) {
    if (ctx.flags.json || ctx.flags.extractMode)
        return;
    ctx.hooks.clearProgressForStdout();
    ctx.io.stderr.write(`${theme.warning("Warning:")} --slides could not extract slide images: ${message}\n`);
    if (isMissingSlidesDependencyError(message)) {
        ctx.io.stderr.write(`${theme.dim("Install ffmpeg + yt-dlp for --slides, and tesseract for --slides-ocr.")}\n`);
    }
    ctx.hooks.restoreProgressAfterStdout?.();
}
export function createUrlFlowProgress({ ctx, theme, }) {
    const { io, flags, hooks } = ctx;
    const oscProgress = createOscProgressController({
        label: "Fetching website",
        env: io.env,
        isTty: flags.progressEnabled,
        write: (data) => io.stderr.write(data),
    });
    oscProgress.setIndeterminate("Fetching website");
    const spinner = startSpinner({
        text: `${theme.label("Fetching website")}${theme.dim(" (connecting)…")}`,
        enabled: flags.progressEnabled,
        stream: io.stderr,
        color: theme.palette.spinner,
    });
    const styleLabel = (text) => theme.label(text);
    const styleDim = (text) => theme.dim(text);
    const renderStatus = (label, detail = "…") => `${styleLabel(label)}${styleDim(detail)}`;
    const renderStatusWithMeta = (label, meta, suffix = "…") => `${styleLabel(label)} ${meta}${styleDim(suffix)}`;
    const renderStatusFromText = (text) => {
        const match = text.match(/^([^:]+):(.*)$/);
        if (!match)
            return styleLabel(text);
        return `${styleLabel(match[1])}${styleDim(`:${match[2]}`)}`;
    };
    const progressStatus = createUrlProgressStatus({
        enabled: flags.progressEnabled,
        spinner,
        oscProgress,
    });
    const handleSignal = () => {
        try {
            spinner.stopAndClear();
        }
        catch {
            // ignore
        }
        oscProgress.clear();
    };
    const handleSigint = () => {
        handleSignal();
        process.exit(130);
    };
    const handleSigterm = () => {
        handleSignal();
        process.exit(143);
    };
    if (flags.progressEnabled) {
        process.once("SIGINT", handleSigint);
        process.once("SIGTERM", handleSigterm);
    }
    const progressHooks = !hooks.onSlidesProgress && flags.progressEnabled
        ? composeUrlFlowHooks(hooks, {
            onSlidesProgress: (text) => {
                const match = text.match(/(\d{1,3})%/);
                const percent = match ? Number(match[1]) : null;
                progressStatus.setSlides(renderStatusFromText(text), Number.isFinite(percent) && percent !== null ? percent : null);
            },
        })
        : hooks;
    const websiteProgress = createWebsiteProgress({
        enabled: flags.progressEnabled,
        spinner,
        oscProgress,
        theme,
    });
    const stopProgress = () => {
        if (!flags.progressEnabled)
            return;
        websiteProgress?.stop?.();
        try {
            spinner.stopAndClear();
        }
        catch {
            // ignore
        }
        oscProgress.clear();
        process.removeListener("SIGINT", handleSigint);
        process.removeListener("SIGTERM", handleSigterm);
    };
    return {
        progressStatus,
        hooks: progressHooks,
        pauseProgress: () => {
            spinner.pause();
            return () => spinner.resume();
        },
        renderStatus,
        renderStatusFromText,
        renderStatusWithMeta,
        spinner,
        styleDim,
        styleLabel,
        handleSigint,
        handleSigterm,
        stopProgress,
        websiteProgress,
    };
}
//# sourceMappingURL=flow-progress.js.map