import { writeFileAtomic } from '../../../infra/config/index.js';
import { assertTraceParams, renderTraceReportFromLogs, renderTraceReportFromRecords, } from './traceReport.js';
export function createTraceReportWriter(params) {
    let traceReportWritten = false;
    return (input) => {
        if (traceReportWritten) {
            params.logger.info('Trace report write skipped because it has already been written', {
                status: input.status,
                iterations: input.iterations,
            });
            return;
        }
        traceReportWritten = true;
        const traceParams = {
            tracePath: params.tracePath,
            workflowName: params.workflowName,
            task: params.task,
            runSlug: params.runSlug,
            status: input.status,
            iterations: input.iterations,
            reason: input.reason,
            endTime: input.endTime,
        };
        assertTraceParams(traceParams);
        let markdown;
        try {
            markdown = renderTraceReportFromLogs(traceParams, params.ndjsonLogPath, params.promptLogPath, params.mode);
        }
        catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            if (!message.startsWith('No session records found for trace report:')) {
                throw error;
            }
            markdown = renderTraceReportFromRecords(traceParams, params.sessionLogger.getNdjsonRecords(), params.sessionLogger.getPromptRecords(), params.mode);
        }
        if (!markdown) {
            return;
        }
        writeFileAtomic(params.tracePath, markdown);
    };
}
//# sourceMappingURL=traceReportWriter.js.map