import { SpanStatusCode } from '@opentelemetry/api';
import { GENAI, NAMZU } from '../../telemetry/attributes.js';
import { toErrorMessage } from '../../utils/error.js';
export class ResultAssembler {
    config;
    constructor(config) {
        this.config = config;
    }
    async *completeRun(rootSpan) {
        const { runMgr, activityStore, log, emitEvent, drainPending } = this.config;
        if (runMgr.status === 'running') {
            runMgr.markCompleted(runMgr.stopReason);
        }
        await emitEvent({
            type: 'run_completed',
            runId: runMgr.id,
            result: runMgr.getRun().result ?? '',
        });
        yield* drainPending();
        rootSpan.setAttributes({
            [NAMZU.RUN_STATUS]: runMgr.stopReason ?? 'completed',
            [NAMZU.ITERATION]: runMgr.currentIteration,
            [GENAI.USAGE_INPUT_TOKENS]: runMgr.tokenUsage.promptTokens,
            [GENAI.USAGE_OUTPUT_TOKENS]: runMgr.tokenUsage.completionTokens,
        });
        rootSpan.setStatus({ code: SpanStatusCode.OK });
        log.info('Query completed', {
            runId: runMgr.id,
            iterations: runMgr.currentIteration,
            stopReason: runMgr.stopReason,
            activityStats: activityStore.enabled ? activityStore.stats() : undefined,
        });
    }
    async *completeSession(rootSpan) {
        yield* this.completeRun(rootSpan);
    }
    async *handleError(err, rootSpan) {
        const { runMgr, planManager, log, emitEvent, drainPending } = this.config;
        const errorMessage = toErrorMessage(err);
        runMgr.markFailed(errorMessage);
        if (planManager.isActive) {
            planManager.failPlan(errorMessage);
        }
        await emitEvent({
            type: 'run_failed',
            runId: runMgr.id,
            error: errorMessage,
        });
        yield* drainPending();
        rootSpan.setAttributes({
            [NAMZU.RUN_STATUS]: 'error',
            [NAMZU.ITERATION]: runMgr.currentIteration,
        });
        rootSpan.setStatus({ code: SpanStatusCode.ERROR, message: errorMessage });
        rootSpan.recordException(err instanceof Error ? err : new Error(errorMessage));
        log.error('Query failed', {
            runId: runMgr.id,
            error: errorMessage,
        });
    }
    async finalize() {
        await this.config.runMgr.persist();
        return this.config.runMgr.getRun();
    }
}
//# sourceMappingURL=result.js.map