import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Box, Text } from "ink";
import { toneColor } from "./design/terminalTheme.js";
const MAX_OUTPUT_LINES = 120;
const MAX_OUTPUT_LINE_CHARS = 240;
export function ShellResultBlock(props) {
    const summary = parseShellResultMessage(props.message);
    if (!summary)
        return null;
    const lines = formatShellOutput(summary.output, MAX_OUTPUT_LINES);
    return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { flexDirection: "row", children: [_jsx(Text, { color: "gray", children: "exit    " }), _jsx(Text, { color: summary.timedOut ? "yellow" : toneColor(props.tone) ?? "gray", children: summary.exit })] }), lines.length > 0 ? (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "gray", children: "output" }), lines.map((line, index) => (_jsx(Text, { color: props.tone === "error" ? "red" : "gray", children: line || " " }, `${index}:${line.slice(0, 24)}`)))] })) : (_jsx(Text, { color: "gray", children: "(No output)" }))] }));
}
export function parseShellResultMessage(message) {
    const lines = message.trim().split(/\r?\n/);
    const first = lines[0]?.trim() ?? "";
    if (!/^(exit\s+(?:\d+|unknown)|timed out)$/i.test(first))
        return null;
    return {
        exit: first.toLowerCase(),
        output: lines.slice(1).join("\n").trim(),
        timedOut: /^timed out$/i.test(first),
    };
}
export function formatShellOutput(output, maxLines = MAX_OUTPUT_LINES) {
    const lines = output.split(/\r?\n/);
    const clipped = lines.length > maxLines;
    const visible = lines.slice(0, maxLines).map((line) => line.length > MAX_OUTPUT_LINE_CHARS
        ? `${line.slice(0, MAX_OUTPUT_LINE_CHARS - 3)}...`
        : line);
    if (clipped)
        visible.push(`... ${lines.length - maxLines} more output lines ...`);
    return visible.filter((line, index, array) => line.length > 0 || index < array.length - 1);
}
