import { appendFileSync } from 'node:fs';
import { join } from 'node:path';
import { PROVIDER_EVENTS_LOG_FILE_SUFFIX } from './contracts.js';
import { normalizeProviderEvent } from './providerEvent.js';
function assertNonEmpty(value, field) {
    if (value.length === 0) {
        throw new Error(`[provider-events] ${field} is required`);
    }
}
export function createProviderEventLogger(config) {
    if (config.enabled) {
        assertNonEmpty(config.logsDir, 'logsDir');
        assertNonEmpty(config.sessionId, 'sessionId');
        assertNonEmpty(config.runId, 'runId');
        assertNonEmpty(config.step, 'step');
    }
    const filepath = join(config.logsDir, `${config.sessionId}${PROVIDER_EVENTS_LOG_FILE_SUFFIX}`);
    let step = config.step;
    let provider = config.provider;
    let hasReportedWriteFailure = false;
    const write = (event) => {
        const record = normalizeProviderEvent(event, provider, step, config.runId);
        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 provider event log: ${message}\n`);
        }
    };
    return {
        filepath,
        setStep(nextStep) {
            assertNonEmpty(nextStep, 'step');
            step = nextStep;
        },
        setProvider(nextProvider) {
            provider = nextProvider;
        },
        wrapCallback(original) {
            if (!config.enabled && original) {
                return original;
            }
            if (!config.enabled) {
                return () => { };
            }
            return (event) => {
                write(event);
                original?.(event);
            };
        },
    };
}
export function isProviderEventsEnabled(config) {
    return config?.logging?.providerEvents === true;
}
//# sourceMappingURL=providerEventLogger.js.map