/**
 * Shared read-only helpers for deriving a run's bounded usage figures from its
 * runtime events. Both the cap monitor (which enforces per-run cost/time caps)
 * and the overview-dashboard projection (which aggregates spend) read usage
 * through these helpers so the cost math has a single source of truth.
 */
/** Upper bound for a single usage figure; anything larger is treated as noise. */
const MAX_SAFE_USAGE_VALUE = 1_000_000_000;
/**
 * Coerce a runtime-event metadata value into a safe, finite, non-negative
 * usage number. Non-numbers, NaN/Infinity, negatives, and absurdly large
 * values collapse to 0 so a malformed event can never distort totals or caps.
 */
export function readSafeUsageNumber(value) {
    if (typeof value !== "number" || !Number.isFinite(value))
        return 0;
    if (value < 0 || value > MAX_SAFE_USAGE_VALUE)
        return 0;
    return value;
}
/**
 * Read every runtime event for a run, following pagination defensively (capped
 * at 10 pages of 100) so a runaway event log cannot stall the read path.
 */
export function listAllRuntimeEvents(localStore, runId) {
    const events = [];
    let cursor;
    for (let pageIndex = 0; pageIndex < 10; pageIndex += 1) {
        const page = localStore.listRuntimeEventsForRun(runId, {
            limit: 100,
            ...(cursor ? { cursor } : {}),
        });
        events.push(...page.events);
        if (!page.nextCursor)
            break;
        cursor = page.nextCursor;
    }
    return events;
}
/** Sum the `usageCostUsd` usage figures reported across a run's events. */
export function sumRunUsageCostUsd(events) {
    return events.reduce((sum, event) => sum + readSafeUsageNumber(event.metadata.usageCostUsd), 0);
}
/** Largest `wallTimeSeconds` usage figure reported across a run's events. */
export function maxRunWallTimeSeconds(events) {
    return events.reduce((max, event) => Math.max(max, readSafeUsageNumber(event.metadata.wallTimeSeconds)), 0);
}
