export function formatMessage(message) {
    switch (message.type) {
        case 'assistant':
            return formatAssistantMessage(message.message.content);
        case 'result':
            return message.subtype === 'success' ? message.result : message.errors.join('\n');
        case 'system':
            // if (message.subtype === 'init') {
            //   return `Claude Code initialized with ${message.model}`;
            // }
            if (message.subtype === 'task_started') {
                return message.description;
            }
            if (message.subtype === 'task_progress') {
                return message.summary || message.description;
            }
            if (message.subtype === 'task_notification') {
                return message.summary;
            }
            if (message.subtype === 'local_command_output') {
                return message.content;
            }
            return null;
        case 'tool_progress':
            return `${message.tool_name} running (${message.elapsed_time_seconds}s)`;
        case 'tool_use_summary':
            return null;
        default:
            return null;
    }
}
function formatAssistantMessage(content) {
    if (typeof content === 'string')
        return content;
    if (!Array.isArray(content))
        return null;
    const parts = content.flatMap((block) => {
        if (!block || typeof block !== 'object')
            return [];
        const typedBlock = block;
        if (typedBlock.type === 'text' && typeof typedBlock.text === 'string') {
            return [typedBlock.text];
        }
        return [];
    });
    return parts.length > 0 ? parts.join('\n') : null;
}
export function extractThinkingEvents(message) {
    if (message.type !== 'assistant' || !Array.isArray(message.message.content))
        return [];
    return message.message.content.flatMap((block) => {
        if (!block || typeof block !== 'object')
            return [];
        const typedBlock = block;
        if (typedBlock.type !== 'thinking' || typeof typedBlock.thinking !== 'string')
            return [];
        const text = typedBlock.thinking.trim();
        return text ? [text] : [];
    });
}
export function extractToolUseEvents(message) {
    if (message.type !== 'assistant' || !Array.isArray(message.message.content))
        return [];
    return message.message.content.flatMap((block) => {
        if (!block || typeof block !== 'object')
            return [];
        const typedBlock = block;
        if (typedBlock.type !== 'tool_use' || typeof typedBlock.name !== 'string')
            return [];
        return [{
                id: typeof typedBlock.id === 'string' ? typedBlock.id : typedBlock.name,
                name: typedBlock.name,
                input: typedBlock.input,
                line: formatToolUse(typedBlock.name, typedBlock.input),
            }];
    });
}
export function extractToolResultEvent(message) {
    if (message.type !== 'user')
        return null;
    const parentToolUseId = message.parent_tool_use_id;
    const toolUseId = typeof parentToolUseId === 'string' && parentToolUseId ? parentToolUseId : undefined;
    const directResult = message.tool_use_result;
    if (directResult !== undefined) {
        return { toolUseId, result: directResult };
    }
    const content = message.message?.content;
    if (Array.isArray(content)) {
        const toolResultBlock = content.find((block) => {
            return Boolean(block && typeof block === 'object' && block.type === 'tool_result');
        });
        if (toolResultBlock) {
            return { toolUseId, result: toolResultBlock.content };
        }
    }
    return null;
}
export function extractClaudeHookEvents(message) {
    const events = [];
    if (message.type === 'system') {
        if (message.subtype === 'task_started') {
            events.push({ event: 'SubagentStart', matcher: '*', payload: message });
        }
        else if (message.subtype === 'task_notification') {
            events.push({ event: 'Notification', matcher: '*', payload: message });
        }
        else if (message.subtype === 'local_command_output') {
            events.push({ event: 'Notification', matcher: 'local_command_output', payload: message });
        }
    }
    if (message.type === 'tool_use_summary') {
        events.push({ event: 'PostToolBatch', matcher: '*', payload: message });
    }
    for (const toolUse of extractToolUseEvents(message)) {
        if (toolUse.name === 'TaskCreate') {
            events.push({ event: 'TaskCreated', matcher: toolUse.name, payload: toolUse });
        }
        if (toolUse.name === 'TaskCompleted') {
            events.push({ event: 'TaskCompleted', matcher: toolUse.name, payload: toolUse });
        }
    }
    return events;
}
export function logToolDebug(message, d, options = {}) {
    switch (message.type) {
        case 'assistant':
            logAssistantToolUses(message.message.content, d);
            return;
        case 'user': {
            const toolResult = message.tool_use_result;
            if (toolResult !== undefined) {
                if (options.suppressAskUserQuestionResult)
                    return;
                d(`tool result | parent=${message.parent_tool_use_id ?? '-'} result=${summarizeToolResult(toolResult)}`);
            }
            return;
        }
        case 'tool_progress':
            d(`tool progress | id=${message.tool_use_id} name=${message.tool_name} elapsed=${message.elapsed_time_seconds}s parent=${message.parent_tool_use_id ?? '-'}`);
            return;
        case 'tool_use_summary':
            d(`tool summary | ids=${message.preceding_tool_use_ids.join(',') || '-'} summary=${truncate(message.summary, 240)}`);
            return;
        case 'system':
            if (message.subtype === 'task_started') {
                d(`subagent started | ${truncate(message.description, 240)}`);
            }
            else if (message.subtype === 'task_progress') {
                d(`subagent progress | ${truncate(message.summary || message.description, 240)}`);
            }
            else if (message.subtype === 'task_notification') {
                d(`subagent notification | ${truncate(message.summary, 240)}`);
            }
            else if (message.subtype === 'local_command_output') {
                d(`local command output | ${truncate(message.content, 240)}`);
            }
            return;
        default:
            return;
    }
}
function logAssistantToolUses(content, d) {
    if (!Array.isArray(content))
        return;
    for (const block of content) {
        if (!block || typeof block !== 'object')
            continue;
        const typedBlock = block;
        if (typedBlock.type !== 'tool_use' || typeof typedBlock.name !== 'string')
            continue;
        const id = typeof typedBlock.id === 'string' ? typedBlock.id : '-';
        d(`tool use | id=${id} name=${typedBlock.name} input=${summarizeToolInput(typedBlock.input) || '-'}`);
    }
}
function formatToolUse(name, input) {
    const summary = summarizeToolInput(input);
    return summary ? `Tool: ${name} ${summary}` : `Tool: ${name}`;
}
function summarizeToolInput(input) {
    if (!input || typeof input !== 'object' || Array.isArray(input))
        return '';
    const record = input;
    const keys = ['file_path', 'path', 'command', 'pattern', 'query', 'description', 'prompt'];
    const details = keys.flatMap((key) => {
        const value = record[key];
        if (typeof value !== 'string' || !value.trim())
            return [];
        return `${key}=${JSON.stringify(truncate(value.trim(), 140))}`;
    });
    if (details.length > 0)
        return details.join(' ');
    return JSON.stringify(redactLargeInput(record));
}
export function truncate(value, max) {
    return value.length > max ? `${value.slice(0, max - 3)}...` : value;
}
function redactLargeInput(input) {
    return Object.fromEntries(Object.entries(input).map(([key, value]) => {
        if (typeof value === 'string')
            return [key, truncate(value, 140)];
        return [key, value];
    }));
}
function summarizeToolResult(result) {
    if (typeof result === 'string')
        return JSON.stringify(truncate(result, 240));
    if (!result || typeof result !== 'object')
        return JSON.stringify(result);
    return JSON.stringify(redactLargeInput(result));
}
export function isAskUserQuestionAutoResult(result) {
    if (typeof result === 'string')
        return /Answer questions\?/i.test(result);
    if (!result || typeof result !== 'object')
        return false;
    return /Answer questions\?/i.test(JSON.stringify(result));
}
export function countUsageTokens(usage) {
    if (!usage || typeof usage !== 'object')
        return 0;
    const values = Object.values(usage);
    return values.reduce((total, value) => total + (typeof value === 'number' ? value : 0), 0);
}
export function formatUsageLine(usage) {
    const normalized = normalizeClaudeUsage(usage);
    if (!normalized)
        return null;
    return [
        `[Usage] tokens=${normalized.totalTokens}`,
        `input=${normalized.inputTokens}`,
        `output=${normalized.outputTokens}`,
        `cached=${normalized.cachedInputTokens}`,
        `reasoning=${normalized.reasoningTokens}`,
    ].join(' ');
}
export function normalizeUsage(usage) {
    const normalized = normalizeClaudeUsage(usage);
    if (!normalized)
        return undefined;
    return {
        inputTokens: normalized.inputTokens,
        outputTokens: normalized.outputTokens,
        cachedInputTokens: normalized.cachedInputTokens,
        reasoningTokens: normalized.reasoningTokens,
        totalTokens: normalized.totalTokens,
    };
}
function normalizeClaudeUsage(usage) {
    if (!usage || typeof usage !== 'object')
        return null;
    const record = usage;
    const inputTokens = numberValue(record.input_tokens);
    const outputTokens = numberValue(record.output_tokens);
    const cachedInputTokens = numberValue(record.cache_read_input_tokens)
        + numberValue(record.cache_creation_input_tokens)
        + numberValue(record.cached_input_tokens);
    const reasoningTokens = numberValue(record.reasoning_output_tokens)
        + numberValue(record.reasoning_tokens);
    const totalTokens = inputTokens + outputTokens + cachedInputTokens + reasoningTokens;
    if (totalTokens === 0)
        return null;
    return { inputTokens, outputTokens, cachedInputTokens, reasoningTokens, totalTokens };
}
function numberValue(value) {
    return typeof value === 'number' && Number.isFinite(value) ? value : 0;
}
//# sourceMappingURL=message-format.js.map