class LogSender {
    constructor(serverUrl = 'http://localhost:3001', appName = 'default-app') {
        this.serverUrl = serverUrl;
        this.appName = appName;
        this.originalConsole = {
            log: console.log,
            error: console.error,
            warn: console.warn,
            info: console.info,
            debug: console.debug
        };
        window.logSender = this;
    }

    // 发送日志到服务器
    async sendLog(level, args) {
        try {
            const timestamp = new Date().toISOString();

            // 改进参数处理：支持结构化数据
            let message;
            let structuredData = {};

            if (args.length > 0) {
                // 检查是否有对象参数，优先处理第一个对象
                let objectIndex = -1;
                for (let i = 0; i < args.length; i++) {
                    if (typeof args[i] === 'object' && args[i] !== null) {
                        objectIndex = i;
                        break;
                    }
                }

                if (objectIndex >= 0) {
                    // 如果有对象参数，将其作为结构化数据，前面的是消息，后面的是附加信息
                    const objectArg = args[objectIndex];
                    structuredData = { data: objectArg };

                    // 前面的参数作为消息
                    const messageParts = args.slice(0, objectIndex).map(arg =>
                        typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
                    );

                    // 后面的参数作为附加消息（如果有）
                    const additionalParts = args.slice(objectIndex + 1).map(arg =>
                        typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
                    );

                    const allMessageParts = [...messageParts, ...additionalParts];
                    message = allMessageParts.join(' ') || 'Object logged';
                } else {
                    // 传统处理方式 - 所有参数都转为字符串拼接
                    message = args.map(arg => {
                        try {
                            return typeof arg === 'object' ? JSON.stringify(arg) : String(arg);
                        } catch {
                            return '[Circular or Non-serializable]';
                        }
                    }).join(' ');
                }
            } else {
                message = '';
            }

            const logData = {
                level: level,
                message: message,
                timestamp: timestamp,
                appName: this.appName,
                userAgent: navigator.userAgent,
                url: window.location.href,
                ...structuredData
            };

            // 使用浏览器 fetch API 发送 POST 请求
            await this.sendHttpRequest(logData);
        } catch (error) {
            // 如果发送失败，仍然输出到控制台
            this.originalConsole.error('Failed to send log to server:', error);
        }
    }

    // HTTP 请求方法 - 使用浏览器 fetch API
    async sendHttpRequest(logData) {
        try {
            const response = await fetch(`${this.serverUrl}/log`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'User-Agent': 'Webhook-Client/1.0'
                },
                body: JSON.stringify(logData)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            return await response.text();
        } catch (error) {
            throw error;
        }
    }

    // 重写 console 方法
    install() {
        const self = this;
        
        console.log = function(...args) {
            self.originalConsole.log.apply(console, args);
            self.sendLog('log', args);
        };

        console.error = function(...args) {
            self.originalConsole.error.apply(console, args);
            self.sendLog('error', args);
        };

        console.warn = function(...args) {
            self.originalConsole.warn.apply(console, args);
            self.sendLog('warn', args);
        };

        console.info = function(...args) {
            self.originalConsole.info.apply(console, args);
            self.sendLog('info', args);
        };

        console.debug = function(...args) {
            self.originalConsole.debug.apply(console, args);
            self.sendLog('debug', args);
        };
        
    }

    // 卸载，重置 console
    uninstall() {
        console.log = this.originalConsole.log;
        console.error = this.originalConsole.error;
        console.warn = this.originalConsole.warn;
        console.info = this.originalConsole.info;
        console.debug = this.originalConsole.debug;
    }

    // 手动发送自定义日志
    async customLog(level, message, data = {}) {
        const logData = {
            level: level,
            message: message,
            timestamp: new Date().toISOString(),
            appName: this.appName,
            userAgent: navigator.userAgent,
            url: window.location.href,
            ...data
        };

        try {
            return await this.sendHttpRequest(logData);
        } catch (error) {
            this.originalConsole.error('Failed to send custom log:', error);
            throw error;
        }
    }
}

// 导出
if (typeof module !== 'undefined' && module.exports) {
    // Node.js 环境
    module.exports = LogSender;
} else if (typeof window !== 'undefined') {
    // 浏览器环境
    window.LogSender = LogSender;
}