import { appendFileSync } from 'node:fs';
import { join } from 'node:path';
import { USAGE_EVENTS_LOG_FILE_SUFFIX } from './contracts.js';
import { buildUsageEventRecord, } from './providerEvent.js';
function assertNonEmpty(value, field) {
    if (value.length === 0) {
        throw new Error(`[usage-events] ${field} is required`);
    }
}
export function createUsageEventLogger(config) {
    if (config.enabled) {
        assertNonEmpty(config.logsDir, 'logsDir');
        assertNonEmpty(config.sessionId, 'sessionId');
        assertNonEmpty(config.runId, 'runId');
        assertNonEmpty(config.providerModel, 'providerModel');
        assertNonEmpty(config.step, 'step');
    }
    const filepath = join(config.logsDir, `${config.sessionId}${USAGE_EVENTS_LOG_FILE_SUFFIX}`);
    let step = config.step;
    let stepType = config.stepType;
    let provider = config.provider;
    let providerModel = config.providerModel;
    let hasReportedWriteFailure = false;
    return {
        filepath,
        setStep(nextStep, nextStepType) {
            assertNonEmpty(nextStep, 'step');
            step = nextStep;
            stepType = nextStepType;
        },
        setProvider(nextProvider, nextProviderModel) {
            assertNonEmpty(nextProviderModel, 'providerModel');
            provider = nextProvider;
            providerModel = nextProviderModel;
        },
        logUsage(params) {
            if (!config.enabled) {
                return;
            }
            const record = buildUsageEventRecord({
                runId: config.runId,
                sessionId: config.sessionId,
                provider,
                providerModel,
                step,
                stepType,
            }, params);
            try {
                appendFileSync(filepath, JSON.stringify(record) + '\n', 'utf-8');
            }
            catch (error) {
                if (hasReportedWriteFailure) {
                    return;
                }
                hasReportedWriteFailure = true;
                const message = error instanceof Error ? error.message : String(error);
                process.stderr.write(`[takt] Failed to write usage event log: ${message}\n`);
            }
        },
    };
}
export function isUsageEventsEnabled(config) {
    return config?.logging?.usageEvents === true;
}
//# sourceMappingURL=usageEventLogger.js.map