import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Box, Text } from "ink";
import { FallbackToolUseErrorMessage, isFallbackToolUseErrorText } from "./FallbackToolUseErrorMessage.js";
import { FallbackToolUseRejectedMessage, isFallbackToolUseRejectedText } from "./FallbackToolUseRejectedMessage.js";
import { MessageResponse } from "./MessageResponse.js";
import { parseApprovalResultMessage } from "./ApprovalResultBlock.js";
import { parseToolResultDetail, ToolResultDetail } from "./ToolResultDetail.js";
import { toneColor } from "./design/terminalTheme.js";
export function ToolResultMessage(props) {
    if (isFallbackToolUseRejectedText(props.text)) {
        return _jsx(FallbackToolUseRejectedMessage, {});
    }
    if (isFallbackToolUseErrorText(props.text)) {
        return _jsx(FallbackToolUseErrorMessage, { result: props.text });
    }
    const status = inferToolResultTone(props.text);
    const title = toolResultDisplayTitle(props.text);
    const rawTitle = toolResultTitle(props.text);
    const body = toolResultBody(props.text);
    return (_jsx(MessageResponse, { tone: status, children: _jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: toneColor(status) ?? "gray", children: title }), _jsx(ToolResultDetail, { title: rawTitle, body: body, tone: status })] }) }));
}
export function inferToolResultTone(text) {
    if (/\bfailed\b|\berror\b|denied|refusing|blocked/i.test(text))
        return "error";
    if (/approval required|awaiting user|paused/i.test(text))
        return "warning";
    if (/\bsucceeded\b|\bdone\b|\bcompleted\b|\bok\b/i.test(text))
        return "success";
    return "default";
}
export function toolResultTitle(text) {
    return text.split(/\r?\n/)[0]?.trim() || "tool result";
}
export function toolResultBody(text) {
    return text.split(/\r?\n/).slice(1).join("\n").trim();
}
export function toolResultDisplayTitle(text) {
    const title = toolResultTitle(text);
    const body = toolResultBody(text);
    if (parseApprovalResultMessage(body) || parseApprovalResultMessage(title))
        return "Permission request";
    if (/^Question awaiting user answer\./i.test(body) || /^Question awaiting user answer\./i.test(title)) {
        return "Question";
    }
    const detail = parseToolResultDetail(title, body);
    if (detail?.action === "EnterPlanMode")
        return "Plan mode";
    if (detail?.action === "ExitPlanMode")
        return "Permission request";
    return title;
}
