"use strict";
/**
 * Result aggregation utilities for headless executor
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractSessionInfo = exports.buildExecutionResult = exports.summarizeToolUsage = void 0;
const ui_1 = require("../../utils/ui");
const WEBSEARCH_FALLBACK_TOOLS = new Set(['Bash', 'WebFetch']);
function summarizeToolUsage(messages) {
    const toolNames = new Set();
    for (const message of messages) {
        const content = message.message?.content || [];
        for (const entry of content) {
            if (entry.type === 'tool_use' && entry.name) {
                toolNames.add(entry.name);
            }
        }
    }
    const orderedToolNames = [...toolNames];
    return {
        toolNames: orderedToolNames,
        calledWebSearch: toolNames.has('WebSearch') || toolNames.has('search'),
        fallbackToolsUsed: orderedToolNames.filter((toolName) => WEBSEARCH_FALLBACK_TOOLS.has(toolName)),
    };
}
exports.summarizeToolUsage = summarizeToolUsage;
/**
 * Build execution result from stream messages
 * @param params - Parameters for building result
 * @returns ExecutionResult with all fields populated
 */
function buildExecutionResult(params) {
    const { exitCode, stdout, stderr, cwd, profile, duration, timedOut, messages } = params;
    const result = {
        exitCode,
        stdout,
        stderr,
        cwd,
        profile,
        duration,
        timedOut,
        success: exitCode === 0 && !timedOut,
        messages,
        toolUsageSummary: summarizeToolUsage(messages),
    };
    // Extract metadata from final 'result' message in stream-json
    const resultMessage = messages.find((m) => m.type === 'result');
    if (resultMessage) {
        result.sessionId = resultMessage.session_id || undefined;
        result.totalCost = resultMessage.total_cost_usd || 0;
        result.numTurns = resultMessage.num_turns || 0;
        result.isError = resultMessage.is_error || false;
        result.type = resultMessage.type || null;
        result.subtype = resultMessage.subtype || undefined;
        result.durationApi = resultMessage.duration_api_ms || 0;
        result.permissionDenials = resultMessage.permission_denials || [];
        result.errors = resultMessage.errors || [];
        result.content = resultMessage.result || '';
    }
    else {
        // Fallback: no result message found (shouldn't happen)
        result.content = stdout;
        if (process.env.CCS_DEBUG) {
            console.error((0, ui_1.warn)('No result message found in stream-json output'));
        }
    }
    return result;
}
exports.buildExecutionResult = buildExecutionResult;
/**
 * Extract session info from result for session management
 * @param result - Execution result
 * @returns Session info or null
 */
function extractSessionInfo(result) {
    if (!result.sessionId) {
        return null;
    }
    return {
        sessionId: result.sessionId,
        totalCost: result.totalCost,
        cwd: result.cwd,
    };
}
exports.extractSessionInfo = extractSessionInfo;
//# sourceMappingURL=result-aggregator.js.map