import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import { Box, Text } from 'ink';
import { useEffect, useReducer } from 'react';
import ToolMessage from '../components/tool-message.js';
import { useTheme } from '../hooks/useTheme.js';
import { getSubagentProgress, subagentProgress, } from '../services/subagent-events.js';
/**
 * Collapse consecutive duplicates into `name (×N)` so a chatty agent that
 * hammers the same tool stays readable.
 */
function groupConsecutive(history) {
    const groups = [];
    for (const name of history) {
        const last = groups[groups.length - 1];
        if (last && last.name === name) {
            last.count++;
        }
        else {
            groups.push({ name, count: 1 });
        }
    }
    return groups;
}
export default function AgentProgress({ subagentName, description, isLive = false, agentId, completedState, }) {
    const { colors } = useTheme();
    const isComplete = !!completedState;
    const [, forceRender] = useReducer((x) => x + 1, 0);
    // Poll the mutable progress state every 100ms
    useEffect(() => {
        if (!isLive || isComplete)
            return;
        const interval = setInterval(() => {
            forceRender();
        }, 100);
        return () => clearInterval(interval);
    }, [isLive, isComplete]);
    // Read current state from the correct progress source
    const progress = agentId ? getSubagentProgress(agentId) : subagentProgress;
    const toolCallCount = isComplete
        ? completedState.toolCallCount
        : progress.toolCallCount;
    const tokenCount = isComplete
        ? completedState.tokenCount
        : progress.tokenCount;
    const toolHistory = isComplete
        ? (completedState.toolHistory ?? [])
        : progress.toolHistory;
    const allGroups = groupConsecutive(toolHistory);
    const MAX_VISIBLE_GROUPS = 3;
    const toolGroups = allGroups.slice(-MAX_VISIBLE_GROUPS);
    const hiddenEarlierCount = Math.max(0, allGroups.length - toolGroups.length);
    const dotColor = isComplete
        ? completedState?.success
            ? colors.success
            : colors.error
        : colors.secondary;
    // Defensive: callers should pass a string, but a malformed model tool call
    // can supply a non-string. Coerce so we never render a raw object/array.
    const safeDescription = typeof description === 'string' ? description : String(description ?? '');
    const terminalWidth = process.stdout.columns || 80;
    const maxDescLen = Math.max(terminalWidth - 4, 40);
    const shortDesc = safeDescription.length > maxDescLen
        ? `${safeDescription.slice(0, maxDescLen)}...`
        : safeDescription;
    const messageContent = (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { color: colors.tool, children: ["\u2692 agent: ", subagentName] }), _jsx(Box, { flexShrink: 1, children: _jsx(Text, { wrap: "truncate-end", color: colors.primary, children: shortDesc }) }), !isComplete && (_jsx(Box, { children: _jsxs(Text, { color: colors.secondary, children: [toolCallCount > 0 ? `${toolCallCount} tool calls` : '', toolCallCount > 0 && tokenCount > 0 ? ' · ' : '', tokenCount > 0 ? `~${tokenCount.toLocaleString()} tokens` : ''] }) })), isComplete && (_jsxs(_Fragment, { children: [_jsxs(Box, { children: [_jsx(Text, { color: colors.secondary, children: "Status: " }), _jsx(Text, { color: dotColor, children: "\u25CF" })] }), _jsx(Box, { children: _jsxs(Text, { color: colors.secondary, children: [completedState.toolCallCount, " tool calls \u00B7 ~", completedState.tokenCount.toLocaleString(), " tokens"] }) })] })), toolGroups.length > 0 && (_jsxs(Box, { flexDirection: "column", marginLeft: 2, children: [hiddenEarlierCount > 0 && (_jsxs(Text, { color: colors.secondary, children: ["\u21B3 + ", hiddenEarlierCount, " earlier"] })), toolGroups.map((g, i) => (_jsxs(Text, { color: colors.secondary, children: ["\u21B3 ", g.name, g.count > 1 ? ` (×${g.count})` : ''] }, `${g.name}-${i}`)))] }))] }));
    return _jsx(ToolMessage, { message: messageContent, hideBox: true });
}
export function MultiAgentProgress({ agents, isLive = false, completedStates, }) {
    return (_jsx(Box, { flexDirection: "column", children: agents.map(agent => (_jsx(Box, { marginBottom: 1, children: _jsx(AgentProgress, { subagentName: agent.subagentName, description: agent.description, isLive: isLive && !completedStates?.has(agent.agentId), agentId: agent.agentId, completedState: completedStates?.get(agent.agentId) }) }, agent.agentId))) }));
}
//# sourceMappingURL=agent-progress.js.map