import { getTextDeltaFromStreamEvent } from "./getTextDeltaFromStreamEvent.js";
import { prettyPrintJson } from "./prettyPrintJson.js";
const TOOL_PROGRESS_EVENTS = [
    ['response.file_search_call.completed', 'success'],
    ['response.file_search_call.in_progress', 'loading'],
    ['response.file_search_call.searching', 'loading'],
    ['response.web_search_call.completed', 'success'],
    ['response.web_search_call.in_progress', 'loading'],
    ['response.web_search_call.searching', 'loading'],
    ['response.code_interpreter_call.completed', 'success'],
    ['response.code_interpreter_call.in_progress', 'loading'],
    ['response.code_interpreter_call.interpreting', 'loading'],
    ['response.image_generation_call.completed', 'success'],
    ['response.image_generation_call.in_progress', 'loading'],
    ['response.image_generation_call.generating', 'loading'],
    ['response.mcp_list_tools.completed', 'success'],
    ['response.mcp_list_tools.in_progress', 'loading'],
];
function getReasoningUpdate(e, data, type, itemId) {
    var _a, _b;
    if (type === 'response.reasoning_text.delta' ||
        type === 'response.reasoning_summary_text.delta') {
        const d = ((_a = e.delta) !== null && _a !== void 0 ? _a : data === null || data === void 0 ? void 0 : data.delta);
        return typeof d === 'string' ? { kind: 'thinking_delta', item_id: itemId, delta: d } : null;
    }
    if (type === 'response.reasoning_text.done' ||
        type === 'response.reasoning_summary_text.done') {
        const text = ((_b = e.text) !== null && _b !== void 0 ? _b : data === null || data === void 0 ? void 0 : data.text);
        return typeof text === 'string' ? { kind: 'thinking_done', item_id: itemId, text } : null;
    }
    return null;
}
function addUpdateForReasoning(id, itemId) {
    const effectiveId = id || (itemId !== null && itemId !== void 0 ? itemId : '');
    return effectiveId ? { kind: 'thinking_add', item_id: effectiveId } : null;
}
function addUpdateForMcpCall(item, id) {
    var _a;
    const name = typeof item.name === 'string' ? item.name : undefined;
    const serverLabel = typeof item.server_label === 'string' ? item.server_label : undefined;
    const args = typeof item.arguments === 'string' ? item.arguments : undefined;
    const mcpRequest = prettyPrintJson(args);
    return Object.assign({ kind: 'tool_add', id, toolName: (_a = name !== null && name !== void 0 ? name : serverLabel) !== null && _a !== void 0 ? _a : 'MCP', serverLabel }, (mcpRequest ? { mcpRequest } : {}));
}
function addUpdateForFunctionCall(item) {
    var _a;
    const callId = typeof item.call_id === 'string' ? item.call_id : ((_a = item.id) !== null && _a !== void 0 ? _a : '');
    const name = typeof item.name === 'string' ? item.name : 'Tool';
    return { kind: 'tool_add', id: callId, toolName: name };
}
function addUpdateForMcpRequest(item, id, status) {
    var _a;
    const name = typeof item.name === 'string' ? item.name : undefined;
    const serverLabel = typeof item.server_label === 'string' ? item.server_label : undefined;
    const args = typeof item.arguments === 'string' ? item.arguments : undefined;
    return {
        kind: 'tool_add',
        id,
        toolName: (_a = name !== null && name !== void 0 ? name : serverLabel) !== null && _a !== void 0 ? _a : 'MCP',
        serverLabel,
        status,
        headerContent: args,
    };
}
function addUpdateForSimpleTool(id, toolName) {
    return id ? { kind: 'tool_add', id, toolName } : null;
}
const OUTPUT_ITEM_TYPE_TO_TOOL_NAME = {
    file_search_call: 'File Search',
    web_search_call: 'Web Search',
    code_interpreter_call: 'Code Interpreter',
    image_generation_call: 'Image Generation',
    mcp_list_tools: 'MCP List Tools',
};
function getUpdateFromOutputItemAdded(e, data, itemId) {
    var _a;
    const item = ((_a = e.item) !== null && _a !== void 0 ? _a : data === null || data === void 0 ? void 0 : data.item);
    if (!item)
        return null;
    const id = typeof item.id === 'string' ? item.id : '';
    if (item.type === 'reasoning')
        return addUpdateForReasoning(id, itemId);
    if (item.type === 'mcp_call')
        return addUpdateForMcpCall(item, id);
    if (item.type === 'function_call')
        return addUpdateForFunctionCall(item);
    if (item.type === 'mcp_approval_request')
        return addUpdateForMcpRequest(item, id, 'waitingConfirmation');
    if (item.type === 'mcp_submission_request')
        return addUpdateForMcpRequest(item, id, 'waitingSubmission');
    const toolName = item.type ? OUTPUT_ITEM_TYPE_TO_TOOL_NAME[item.type] : undefined;
    if (toolName)
        return addUpdateForSimpleTool(id, toolName);
    return null;
}
function getReasoningDoneUpdate(item) {
    var _a, _b, _c, _d, _e;
    if (item.type !== 'reasoning' || typeof item.id !== 'string')
        return null;
    const reasoning = item;
    const texts = (_d = (_b = (_a = reasoning.content) === null || _a === void 0 ? void 0 : _a.map((c) => c.text).filter((t) => typeof t === 'string')) !== null && _b !== void 0 ? _b : (_c = reasoning.summary) === null || _c === void 0 ? void 0 : _c.map((s) => s.text).filter((t) => typeof t === 'string')) !== null && _d !== void 0 ? _d : [];
    const text = texts.length <= 1 ? ((_e = texts[0]) !== null && _e !== void 0 ? _e : '') : texts.join('\n\n');
    return { kind: 'thinking_done', item_id: reasoning.id, text };
}
function mcpOutputIndicatesApplicationError(output) {
    if (!output)
        return false;
    return /\berror\s*=\s*["']true["']/.test(output);
}
function mcpTerminalToolStatus(errStr, outputStr) {
    if (errStr || mcpOutputIndicatesApplicationError(outputStr)) {
        return 'error';
    }
    return 'success';
}
function getMcpCallDoneUpdate(item) {
    var _a;
    if (item.type !== 'mcp_call' || typeof item.id !== 'string')
        return null;
    const mcp = item;
    const st = (_a = mcp.status) !== null && _a !== void 0 ? _a : '';
    const outputStr = typeof mcp.output === 'string' ? mcp.output : undefined;
    const errStr = typeof mcp.error === 'string' ? mcp.error : undefined;
    const argsStr = typeof mcp.arguments === 'string' ? mcp.arguments : undefined;
    let status = 'loading';
    if (st === 'failed' || st === 'incomplete') {
        status = 'error';
    }
    else if (st === 'completed' || st === 'complete') {
        status = mcpTerminalToolStatus(errStr, outputStr);
    }
    else if (errStr) {
        status = 'error';
    }
    else if (outputStr !== undefined) {
        status = mcpTerminalToolStatus(errStr, outputStr);
    }
    let toolName;
    if (typeof mcp.name === 'string')
        toolName = mcp.name;
    else if (typeof mcp.server_label === 'string')
        toolName = mcp.server_label;
    else
        toolName = undefined;
    const mcpRequest = prettyPrintJson(argsStr);
    const mcpResponse = prettyPrintJson(errStr !== null && errStr !== void 0 ? errStr : outputStr);
    return Object.assign(Object.assign({ kind: 'tool_update', item_id: mcp.id, status,
        toolName, output: outputStr, error: errStr }, (mcpRequest ? { mcpRequest } : {})), (mcpResponse ? { mcpResponse } : {}));
}
function getFunctionCallDoneUpdate(item) {
    if (item.type !== 'function_call')
        return null;
    const fn = item;
    const fnCallId = fn.call_id ? fn.call_id : '';
    if (!fnCallId)
        return null;
    let fnStatus = 'loading';
    if (fn.status === 'completed') {
        fnStatus = 'success';
    }
    else if (fn.status === 'failed') {
        fnStatus = 'error';
    }
    let output;
    if (typeof fn.output === 'string') {
        output = fn.output;
    }
    else if (typeof fn.result === 'string') {
        output = fn.result;
    }
    else {
        output = undefined;
    }
    return {
        kind: 'tool_update',
        item_id: fnCallId,
        status: fnStatus,
        toolName: typeof fn.name === 'string' ? fn.name : undefined,
        output,
        error: typeof fn.error === 'string' ? fn.error : undefined,
    };
}
function getToolCallDoneUpdate(item, toolName) {
    if (typeof item.id !== 'string')
        return null;
    const t = item;
    let status = 'loading';
    if (t.status === 'completed')
        status = 'success';
    else if (t.status === 'failed' || t.status === 'incomplete')
        status = 'error';
    let output;
    if (typeof t.output === 'string') {
        output = t.output;
    }
    else if (typeof t.results === 'string') {
        output = t.results;
    }
    else if (Array.isArray(t.results)) {
        output = JSON.stringify(t.results);
    }
    else {
        output = undefined;
    }
    return {
        kind: 'tool_update',
        item_id: t.id,
        status,
        toolName,
        output,
        error: typeof t.error === 'string' ? t.error : undefined,
    };
}
function getUpdateFromOutputItemDone(e, data) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const item = ((_a = e.item) !== null && _a !== void 0 ? _a : data === null || data === void 0 ? void 0 : data.item);
    if (!item)
        return null;
    return ((_h = (_g = (_f = (_e = (_d = (_c = (_b = getReasoningDoneUpdate(item)) !== null && _b !== void 0 ? _b : getMcpCallDoneUpdate(item)) !== null && _c !== void 0 ? _c : getFunctionCallDoneUpdate(item)) !== null && _d !== void 0 ? _d : (item.type === 'file_search_call' ? getToolCallDoneUpdate(item, 'File Search') : null)) !== null && _e !== void 0 ? _e : (item.type === 'web_search_call' ? getToolCallDoneUpdate(item, 'Web Search') : null)) !== null && _f !== void 0 ? _f : (item.type === 'code_interpreter_call'
        ? getToolCallDoneUpdate(item, 'Code Interpreter')
        : null)) !== null && _g !== void 0 ? _g : (item.type === 'image_generation_call'
        ? getToolCallDoneUpdate(item, 'Image Generation')
        : null)) !== null && _h !== void 0 ? _h : (item.type === 'mcp_list_tools' ? getToolCallDoneUpdate(item, 'MCP List Tools') : null));
}
/** Stream event → content update (text delta, tool add/update, thinking add/delta/done) or null. */
export function getStreamEventContentUpdate(event) {
    var _a, _b, _c;
    if (!event)
        return null;
    const e = event;
    const type = (_c = (_a = e.type) !== null && _a !== void 0 ? _a : (_b = e.data) === null || _b === void 0 ? void 0 : _b.type) !== null && _c !== void 0 ? _c : e.event;
    const data = e.data;
    const itemId = typeof e.item_id === 'string' ? e.item_id : data === null || data === void 0 ? void 0 : data.item_id;
    const delta = getTextDeltaFromStreamEvent(event);
    if (delta)
        return { kind: 'text_delta', delta };
    if (itemId) {
        const reasoningUpdate = getReasoningUpdate(e, data, type, itemId);
        if (reasoningUpdate)
            return reasoningUpdate;
    }
    if (type === 'response.output_item.added') {
        return getUpdateFromOutputItemAdded(e, data, itemId);
    }
    if (type === 'response.mcp_call.completed' && itemId) {
        return { kind: 'tool_update', item_id: itemId, status: 'success' };
    }
    if (type === 'response.mcp_call.failed' && itemId) {
        const err = typeof e.error === 'string' ? e.error : undefined;
        return { kind: 'tool_update', item_id: itemId, status: 'error', error: err };
    }
    const progressMatch = TOOL_PROGRESS_EVENTS.find(([t]) => t === type);
    if (progressMatch && itemId) {
        return { kind: 'tool_update', item_id: itemId, status: progressMatch[1] };
    }
    if (type === 'response.mcp_list_tools.failed' && itemId) {
        const err = typeof e.error === 'string' ? e.error : undefined;
        return { kind: 'tool_update', item_id: itemId, status: 'error', error: err };
    }
    if (type === 'response.output_item.done') {
        return getUpdateFromOutputItemDone(e, data);
    }
    return null;
}
//# sourceMappingURL=getStreamEventContentUpdate.js.map
