import { runAgent } from '../../tools/run_agent.js';
// ─── Helpers ──────────────────────────────────────────────────────────────────
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function extractResultText(result) {
    if (Array.isArray(result?.content)) {
        return result.content
            .filter((c) => c.type === 'text')
            .map((c) => c.text)
            .join('\n');
    }
    return String(result ?? '');
}
// ─── Core logic ────────────────────────────────────────────────────────────────
export async function runAgentsLocally(agents, opts) {
    const { waitAll } = opts;
    const startTime = Date.now();
    const controllers = agents.map(() => new AbortController());
    const settled = new Array(agents.length).fill(false);
    const promises = agents.map(async (agentArgs, index) => {
        const label = agentArgs.taskId || agentArgs.agentName || `task_${index + 1}`;
        const taskStart = Date.now();
        try {
            const result = await runAgent({ ...agentArgs, signal: controllers[index].signal });
            settled[index] = true;
            const elapsed = ((Date.now() - taskStart) / 1000).toFixed(1);
            const text = extractResultText(result);
            return {
                label,
                runner: agentArgs.runner,
                agentName: agentArgs.agentName,
                status: result?.isError ? 'error' : 'success',
                elapsed: `${elapsed}s`,
                result: text,
            };
        }
        catch (err) {
            settled[index] = true;
            const elapsed = ((Date.now() - taskStart) / 1000).toFixed(1);
            const msg = err instanceof Error ? err.message : String(err);
            return {
                label,
                runner: agentArgs.runner,
                agentName: agentArgs.agentName,
                status: 'error',
                elapsed: `${elapsed}s`,
                result: msg,
            };
        }
    });
    if (waitAll) {
        const settledResults = await Promise.allSettled(promises);
        const results = settledResults.map((s, i) => {
            const label = agents[i].taskId || agents[i].agentName || `task_${i + 1}`;
            if (s.status === 'fulfilled')
                return s.value;
            return {
                label,
                runner: agents[i].runner,
                agentName: agents[i].agentName,
                status: 'error',
                elapsed: '?',
                result: s.reason instanceof Error ? s.reason.message : String(s.reason),
            };
        });
        const totalElapsed = ((Date.now() - startTime) / 1000).toFixed(1);
        const successCount = results.filter((r) => r.status === 'success').length;
        const errorCount = results.filter((r) => r.status === 'error').length;
        const summary = [
            `⚡ run_agents_parallel — ${results.length} agent(s) | ✅ ${successCount} succès | ❌ ${errorCount} erreurs | 🕐 ${totalElapsed}s total`,
            '',
            ...results.map((r) => {
                const icon = r.status === 'success' ? '✅' : '❌';
                const header = `${icon} [${r.label}] ${r.runner}${r.agentName ? `/${r.agentName}` : ''} (${r.elapsed})`;
                return `${header}\n${r.result}`;
            }),
        ].join('\n---\n');
        return {
            content: [{ type: 'text', text: summary }],
            isError: errorCount === results.length,
        };
    }
    else {
        // Race mode: get first result, abort others, AND catch unhandled rejections
        const firstResult = await Promise.race(promises);
        // Abort all unsettled agents
        for (let i = 0; i < controllers.length; i++) {
            if (!settled[i]) {
                controllers[i].abort();
            }
        }
        // Catch any remaining promises to prevent unhandled rejections
        // (they may reject after being aborted)
        for (let i = 0; i < promises.length; i++) {
            if (!settled[i]) {
                promises[i].catch(() => { }); // Silently absorb abort rejections
            }
        }
        const totalElapsed = ((Date.now() - startTime) / 1000).toFixed(1);
        const singleResult = [firstResult];
        const successCount = singleResult.filter((r) => r.status === 'success').length;
        const errorCount = singleResult.filter((r) => r.status === 'error').length;
        const summary = [
            `⚡ run_agents_parallel — ${singleResult.length} agent(s) | ✅ ${successCount} succès | ❌ ${errorCount} erreurs | 🕐 ${totalElapsed}s total`,
            '',
            ...singleResult.map((r) => {
                const icon = r.status === 'success' ? '✅' : '❌';
                const header = `${icon} [${r.label}] ${r.runner}${r.agentName ? `/${r.agentName}` : ''} (${r.elapsed})`;
                return `${header}\n${r.result}`;
            }),
        ].join('\n---\n');
        return {
            content: [{ type: 'text', text: summary }],
            isError: errorCount === singleResult.length,
        };
    }
}
// ─── Dispatcher ────────────────────────────────────────────────────────────────
export async function dispatchAgents(agents, opts) {
    return runAgentsLocally(agents, opts);
}
//# sourceMappingURL=dispatcher.js.map