/*
 * Copyright OpenSearch Contributors
 * SPDX-License-Identifier: Apache-2.0
 */
import { debug } from '../../lib/debug.js';
import { fetchTracesByRunIds } from './index.js';
/**
 * Hard ceiling on `maxAttempts`, mirroring the constant in
 * `services/traces/tracePoller.ts`. Prevents a misconfigured agent
 * (e.g. `tracePolling.maxAttempts: 10_000`) from blocking a test body
 * indefinitely.
 */
export const SDK_TRACE_POLL_CEILING = 60;
const envInt = (name, fallback) => {
    const raw = process.env?.[name];
    if (!raw)
        return fallback;
    const n = parseInt(raw, 10);
    return Number.isFinite(n) && n > 0 ? n : fallback;
};
/** Default interval between polling attempts. ~1s for SDK interactivity. */
export const SDK_DEFAULT_POLL_INTERVAL_MS = envInt('TRACE_POLL_INTERVAL_MS', 1000);
/** Default attempt budget. 10 attempts × ~1s ≈ 10s total for SDK pre-load. */
export const SDK_DEFAULT_MAX_ATTEMPTS = envInt('TRACE_POLL_MAX_ATTEMPTS', 10);
/**
 * Poll for spans associated with a single agent runId. Resolves with
 * the spans on the first non-empty fetch, or with `{ spans: [],
 * lastError? }` after `maxAttempts` of empty / failing responses.
 * Never throws.
 */
export async function fetchSpansForRun(runId, options = {}) {
    const requestedMax = options.maxAttempts ?? SDK_DEFAULT_MAX_ATTEMPTS;
    const maxAttempts = Math.max(1, Math.min(requestedMax, SDK_TRACE_POLL_CEILING));
    const intervalMs = Math.max(0, options.intervalMs ?? SDK_DEFAULT_POLL_INTERVAL_MS);
    let lastError;
    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
        try {
            const result = await fetchTracesByRunIds([runId]);
            if (result?.spans && result.spans.length > 0) {
                debug('FetchSpansForRun', `runId=${runId} attempt=${attempt} found ${result.spans.length} spans`);
                return { spans: result.spans };
            }
            // Successful fetch but no spans yet — clear any previous transient
            // error so the caller doesn't blame a long-since-recovered hiccup.
            lastError = undefined;
            debug('FetchSpansForRun', `runId=${runId} attempt=${attempt}/${maxAttempts} empty`);
        }
        catch (err) {
            // Capture the message but keep retrying — the caller decides
            // whether to surface it as `unavailableTracesAccessor` reason.
            lastError = err instanceof Error ? err.message : String(err);
            debug('FetchSpansForRun', `runId=${runId} attempt=${attempt} fetch error: ${lastError}`);
        }
        if (attempt < maxAttempts && intervalMs > 0) {
            await new Promise(resolve => setTimeout(resolve, intervalMs));
        }
    }
    return { spans: [], lastError };
}
//# sourceMappingURL=fetchSpansForRun.js.map