import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Box, Text } from "ink";
import { CtrlOToExpand } from "./CtrlOToExpand.js";
import { MessageResponse } from "./MessageResponse.js";
const MAX_RENDERED_LINES = 10;
export function FallbackToolUseErrorMessage(props) {
    const model = fallbackToolUseErrorModel(props.result, Boolean(props.verbose));
    return (_jsx(MessageResponse, { tone: "error", children: _jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: model.body }), model.hiddenLines > 0 ? (_jsxs(Box, { children: [_jsx(Text, { dimColor: true, children: `... +${model.hiddenLines} ${model.hiddenLines === 1 ? "line" : "lines"} ` }), _jsx(CtrlOToExpand, {})] })) : null] }) }));
}
export function fallbackToolUseErrorModel(result, verbose = false, maxRenderedLines = MAX_RENDERED_LINES) {
    const error = normalizeToolUseError(result, verbose);
    const lines = error.split(/\r?\n/);
    const visible = verbose ? lines : lines.slice(0, maxRenderedLines);
    return {
        body: visible.join("\n"),
        hiddenLines: verbose ? 0 : Math.max(0, lines.length - visible.length),
    };
}
export function isFallbackToolUseErrorText(text) {
    return /<tool_use_error>|<\/?error>|InputValidationError:|tool execution failed/i.test(text);
}
function normalizeToolUseError(result, verbose) {
    if (typeof result !== "string")
        return "Tool execution failed";
    const extracted = extractTaggedContent(result, "tool_use_error") ?? result;
    const withoutSandbox = extracted.replace(/<sandbox_violation[\s\S]*?<\/sandbox_violation>/gi, "");
    const withoutTags = withoutSandbox
        .replace(/<\/?error>/gi, "")
        .replace(/<\/?tool_use_error>/gi, "")
        .replace(/\x1b\[[0-9;]*m/g, "")
        .trim();
    if (!verbose && withoutTags.includes("InputValidationError: ")) {
        return "Invalid tool parameters";
    }
    if (!withoutTags)
        return "Tool execution failed";
    if (/^(Error|Cancelled):\s/i.test(withoutTags))
        return withoutTags;
    return `Error: ${withoutTags}`;
}
function extractTaggedContent(text, tag) {
    const pattern = new RegExp(`<${tag}>([\\s\\S]*?)<\\/${tag}>`, "i");
    return pattern.exec(text)?.[1];
}
