const mergeModelEntry = (existing, message) => {
    if (existing.provider === undefined && message.provider !== undefined) {
        existing.provider = message.provider;
    }
};
const collectFromMessages = (messages, seen) => {
    var _a;
    for (const m of messages) {
        if (m.role === 'assistant' && m.model) {
            const existing = seen.get(m.model);
            if (!existing) {
                seen.set(m.model, {
                    model: m.model,
                    provider: m.provider,
                });
            }
            else {
                mergeModelEntry(existing, m);
            }
        }
        for (const tc of (_a = m.toolCalls) !== null && _a !== void 0 ? _a : []) {
            if (tc.subAgentTrace)
                collectFromMessages(tc.subAgentTrace, seen);
        }
    }
};
const providerByModelFromStatuses = (providerStatuses) => {
    var _a, _b;
    const map = new Map();
    for (const entry of providerStatuses) {
        const model = (_a = entry.status) === null || _a === void 0 ? void 0 : _a.model;
        const provider = (_b = entry.status) === null || _b === void 0 ? void 0 : _b.provider;
        if (model && provider) {
            map.set(model, provider);
        }
    }
    return map;
};
/** Unique models used across a message list (includes sub-agent traces). */
export function collectSessionModels(messages, providerStatuses = []) {
    if (providerStatuses.length === 0) {
        console.warn('collectSessionModels called without providerStatuses. Registry provider fallback unavailable.');
    }
    const seen = new Map();
    collectFromMessages(messages, seen);
    const providerByModel = providerByModelFromStatuses(providerStatuses);
    return [...seen.values()].map(({ model, provider }) => ({
        model,
        provider: provider !== null && provider !== void 0 ? provider : providerByModel.get(model),
    }));
}
