import { readFileSync } from 'node:fs';
import { saveSessionState } from '../../../infra/config/index.js';
import { getLabel } from '../../../shared/i18n/index.js';
import { getErrorMessage } from '../../../shared/utils/error.js';
import { notifyError, notifySuccess } from '../../../shared/utils/index.js';
import { USAGE_MISSING_REASONS } from '../../../core/logging/contracts.js';
import { formatElapsedTime, truncate } from './workflowExecutionUtils.js';
function buildSessionStateWarning(projectCwd, workflowName, task, error) {
    return [
        `Failed to save session state for workflow "${workflowName}"`,
        `task "${truncate(task, 200)}"`,
        `in ${projectCwd}: ${getErrorMessage(error)}`,
    ].join(' ');
}
export function finalizeWorkflowSuccess(sessionLog, task, workflowName, lastStepContent, lastStepName, projectCwd, onWarning) {
    const finalized = {
        ...sessionLog,
        status: 'completed',
        endTime: new Date().toISOString(),
    };
    try {
        saveSessionState(projectCwd, {
            status: 'success',
            taskResult: truncate(lastStepContent ?? '', 1000),
            timestamp: new Date().toISOString(),
            workflowName,
            taskContent: truncate(task, 200),
            lastStep: lastStepName,
        });
    }
    catch (error) {
        onWarning?.(buildSessionStateWarning(projectCwd, workflowName, task, error));
    }
    return finalized;
}
export function finalizeWorkflowAbort(sessionLog, reason, task, workflowName, lastStepName, projectCwd, onWarning) {
    const finalized = {
        ...sessionLog,
        status: 'aborted',
        endTime: new Date().toISOString(),
    };
    try {
        saveSessionState(projectCwd, {
            status: reason === 'user_interrupted' ? 'user_stopped' : 'error',
            errorMessage: reason,
            timestamp: new Date().toISOString(),
            workflowName,
            taskContent: truncate(task, 200),
            lastStep: lastStepName,
        });
    }
    catch (error) {
        onWarning?.(buildSessionStateWarning(projectCwd, workflowName, task, error));
    }
    return finalized;
}
export function reportStepFile(filePath, fileName, out) {
    out.logLine(`\n📄 Report: ${fileName}\n`);
    out.logLine(readFileSync(filePath, 'utf-8'));
}
export function reportWorkflowCompletion(out, sessionLog, iteration, ndjsonLogPath, shouldNotifyWorkflowComplete) {
    const elapsed = sessionLog.endTime ? formatElapsedTime(sessionLog.startTime, sessionLog.endTime) : '';
    out.success(`Workflow completed (${iteration} iterations${elapsed ? `, ${elapsed}` : ''})`);
    out.info(`Session log: ${ndjsonLogPath}`);
    if (shouldNotifyWorkflowComplete) {
        notifySuccess('TAKT', getLabel('workflow.notifyComplete', undefined, { iteration: String(iteration) }));
    }
}
export function reportWorkflowAbort(out, sessionLog, iteration, reason, ndjsonLogPath, shouldNotifyWorkflowAbort) {
    const elapsed = sessionLog.endTime ? formatElapsedTime(sessionLog.startTime, sessionLog.endTime) : '';
    out.error(`Workflow aborted after ${iteration} iterations${elapsed ? ` (${elapsed})` : ''}: ${reason}`);
    out.info(`Session log: ${ndjsonLogPath}`);
    if (shouldNotifyWorkflowAbort) {
        notifyError('TAKT', getLabel('workflow.notifyAbort', undefined, { reason }));
    }
}
export function updateUsageForStepCompletion(usageEventLogger, response) {
    usageEventLogger.logUsage({
        success: response.status === 'done',
        usage: response.providerUsage ?? { usageMissing: true, reason: USAGE_MISSING_REASONS.NOT_AVAILABLE },
    });
}
//# sourceMappingURL=workflowExecutionReporting.js.map