/**
 * 基础事件序列化器接口
 * 定义统一的序列化/反序列化规范
 */
/**
 * 基础事件序列化器抽象类
 * 提供通用的序列化功能实现
 */
export class BaseEventSerializer {
    options;
    constructor(options = {}) {
        this.options = {
            includeTimestamp: true,
            includeEventId: true,
            ...options
        };
    }
    /**
     * 序列化事件为SSE wire格式
     */
    serializeToWire(event) {
        const lines = [];
        // 添加事件类型
        const eventType = this.extractEventType(event);
        lines.push(`event: ${eventType}`);
        // 添加事件数据
        const data = this.extractEventData(event);
        if (data !== null && data !== undefined) {
            const dataStr = this.serializeData(data);
            lines.push(`data: ${dataStr}`);
        }
        // 添加时间戳
        if (this.options.includeTimestamp) {
            const timestamp = this.extractTimestamp(event) || this.generateTimestamp();
            lines.push(`id: ${timestamp}`);
        }
        // 添加事件ID（如果与时间戳不同）
        if (this.options.includeEventId && this.options.includeTimestamp) {
            const eventId = this.extractEventId(event) || this.options.eventIdGenerator?.();
            if (eventId) {
                lines.push(`id: ${eventId}`);
            }
        }
        // SSE事件以空行结束
        lines.push('');
        return lines.join('\n');
    }
    /**
     * 从SSE wire格式反序列化事件
     */
    deserializeFromWire(wireData) {
        const lines = wireData.trim().split('\n');
        let eventType = null;
        let eventData = null;
        let eventId = null;
        let timestamp = null;
        for (const line of lines) {
            if (line.startsWith('event:')) {
                eventType = line.substring(6).trim();
            }
            else if (line.startsWith('data:')) {
                const dataStr = line.substring(5).trim();
                eventData = this.deserializeData(dataStr);
            }
            else if (line.startsWith('id:')) {
                const idValue = line.substring(3).trim();
                // 第一个id通常是时间戳，第二个是事件ID
                if (!timestamp) {
                    timestamp = idValue;
                }
                else {
                    eventId = idValue;
                }
            }
        }
        if (!eventType) {
            throw new Error('Missing event type in SSE data');
        }
        return this.createEvent(eventType, eventData, timestamp, eventId);
    }
    /**
     * 验证SSE wire格式
     */
    validateWireFormat(wireData) {
        try {
            const lines = wireData.trim().split('\n');
            let hasEvent = false;
            let hasData = false;
            for (const line of lines) {
                if (line.startsWith('event:')) {
                    hasEvent = true;
                }
                else if (line.startsWith('data:')) {
                    hasData = true;
                }
            }
            return hasEvent && hasData;
        }
        catch {
            return false;
        }
    }
    /**
     * 生成当前时间戳
     */
    generateTimestamp() {
        return new Date().toISOString();
    }
    /**
     * 序列化数据
     */
    serializeData(data) {
        if (typeof data === 'string') {
            return data;
        }
        return JSON.stringify(data, this.options.jsonReplacer);
    }
    /**
     * 反序列化数据
     */
    deserializeData(dataStr) {
        try {
            return JSON.parse(dataStr, this.options.jsonReviver);
        }
        catch {
            return dataStr;
        }
    }
    /**
     * 从事件对象中提取时间戳
     */
    extractTimestamp(event) {
        return null;
    }
    /**
     * 从事件对象中提取事件ID
     */
    extractEventId(event) {
        return null;
    }
}
/**
 * 序列化错误类
 */
export class SerializationError extends Error {
    cause;
    eventData;
    constructor(message, cause, eventData) {
        super(message);
        this.cause = cause;
        this.eventData = eventData;
        this.name = 'SerializationError';
    }
}
/**
 * 批量序列化工具
 */
export class BatchSerializer {
    serializer;
    constructor(serializer) {
        this.serializer = serializer;
    }
    /**
     * 批量序列化事件
     */
    async serializeBatch(events) {
        const results = [];
        for (const event of events) {
            const startTime = Date.now();
            let wireData;
            let error;
            try {
                wireData = this.serializer.serializeToWire(event);
            }
            catch (e) {
                error = e instanceof Error ? e.message : String(e);
                wireData = '';
            }
            results.push({
                wireData,
                stats: {
                    duration: Date.now() - startTime,
                    size: new Blob([wireData]).size,
                    success: !error,
                    error
                }
            });
        }
        return results;
    }
    /**
     * 批量反序列化事件
     */
    async deserializeBatch(wireDataArray) {
        const events = [];
        for (const wireData of wireDataArray) {
            try {
                if (this.serializer.validateWireFormat(wireData)) {
                    const event = this.serializer.deserializeFromWire(wireData);
                    events.push(event);
                }
            }
            catch (e) {
                // 跳过无法反序列化的事件，或者可以选择抛出错误
                console.warn('Failed to deserialize event:', e);
            }
        }
        return events;
    }
}
