import { buildSuperintendentLog } from "../row-builder.js";
export function createSuperintendentCallbacks(client) {
    return {
        runRole: (role, name, run) => traceRole(client, role, name, run)
    };
}
async function traceRole(client, role, name, run) {
    let executionStarted = false;
    let executionError;
    let executionResult;
    try {
        const sdk = await client.getSdk();
        const traced = resolveTraced(sdk);
        const currentSpan = resolveCurrentSpan(sdk);
        return await traced(async () => {
            executionStarted = true;
            const span = currentSpan();
            try {
                executionResult = await run();
                span.log(buildSuperintendentLog(role, executionResult));
                return executionResult;
            }
            catch (error) {
                executionError = error;
                span.log({
                    metadata: {
                        role,
                        ...(name === undefined ? {} : { name }),
                        error: error instanceof Error ? error.message : String(error)
                    },
                    scores: { passed: 0 }
                });
                throw error;
            }
        }, {
            name: name === undefined ? `role:${role}` : `role:${role}:${name}`,
            type: "task"
        });
    }
    catch (error) {
        if (executionError !== undefined) {
            throw executionError;
        }
        client.recordError(error, `superintendent ${role}`);
        if (executionStarted) {
            return executionResult;
        }
        return run();
    }
}
function resolveTraced(sdk) {
    if (sdk === undefined || typeof sdk.traced !== "function") {
        throw new Error("Braintrust SDK traced unavailable");
    }
    return sdk.traced;
}
function resolveCurrentSpan(sdk) {
    if (sdk === undefined || typeof sdk.currentSpan !== "function") {
        throw new Error("Braintrust SDK current span unavailable");
    }
    return sdk.currentSpan;
}
