import { buildProbeContext } from '../probe/context.js';
import { probe as defaultProbeRegistry } from '../probe/registry.js';
let providerCallCounter = 0;
function nextCallId() {
    providerCallCounter += 1;
    return `pcall_${Date.now().toString(36)}${providerCallCounter.toString(36)}`;
}
function extractStreamUsage(usage) {
    if (!usage)
        return undefined;
    const u = usage;
    return {
        inputTokens: u.inputTokens ?? u.promptTokens,
        outputTokens: u.outputTokens ?? u.completionTokens,
        totalTokens: u.totalTokens,
        costUsd: u.costUsd,
    };
}
export function wrapProviderWithProbes(provider, opts = {}) {
    const probes = opts.probes ?? defaultProbeRegistry;
    const runId = opts.runId;
    const wrapped = {
        id: provider.id,
        name: provider.name,
        listModels: provider.listModels?.bind(provider),
        healthCheck: provider.healthCheck?.bind(provider),
        async *chatStream(params) {
            const callId = nextCallId();
            const ctx = buildProbeContext({ runId });
            const startedAt = Date.now();
            probes.dispatch({
                type: 'provider_call_start',
                providerId: provider.id,
                model: params.model,
                callId,
                runId,
            }, ctx);
            try {
                let lastUsage;
                for await (const chunk of provider.chatStream(params)) {
                    if (chunk.usage)
                        lastUsage = chunk.usage;
                    yield chunk;
                }
                probes.dispatch({
                    type: 'provider_call_completed',
                    providerId: provider.id,
                    model: params.model,
                    callId,
                    runId,
                    durationMs: Date.now() - startedAt,
                    usage: extractStreamUsage(lastUsage),
                }, ctx);
            }
            catch (error) {
                probes.dispatch({
                    type: 'provider_call_failed',
                    providerId: provider.id,
                    model: params.model,
                    callId,
                    runId,
                    durationMs: Date.now() - startedAt,
                    error: error instanceof Error ? error.message : String(error),
                }, ctx);
                throw error;
            }
        },
    };
    return wrapped;
}
//# sourceMappingURL=instrumentation.js.map