const http = require('http');
const { URL } = require('url');

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
        };
    }

    // 发送日志到服务器
    async sendLog(level, args) {
        try {
            const timestamp = new Date().toISOString();
            const message = args.map(arg =>
                typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
            ).join(' ');

            const logData = {
                level: level,
                message: message,
                timestamp: timestamp,
                appName: this.appName,
                userAgent: 'Node.js',
                url: 'Node.js'
            };

            // 使用 Node.js http 模块发送 GET 请求
            await this.sendHttpRequest(logData);
        } catch (error) {
            // 如果发送失败，仍然输出到控制台
            this.originalConsole.error('Failed to send log to server:', error);
        }
    }

    // HTTP 请求方法
    async sendHttpRequest(logData) {
        return new Promise((resolve, reject) => {
            // 手动构建查询字符串，避免URLSearchParams问题
            const queryString = Object.keys(logData)
                .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(logData[key])}`)
                .join('&');
            const requestUrl = `${this.serverUrl}/log?${queryString}`;
            
            const parsedUrl = new URL(requestUrl);
            const options = {
                hostname: parsedUrl.hostname,
                port: parsedUrl.port,
                path: parsedUrl.pathname + parsedUrl.search,
                method: 'GET',
                headers: {
                    'User-Agent': 'Webhook-Client/1.0'
                }
            };

            const req = http.request(options, (res) => {
                let data = '';
                res.on('data', (chunk) => {
                    data += chunk;
                });
                res.on('end', () => {
                    if (res.statusCode >= 200 && res.statusCode < 300) {
                        resolve(data);
                    } else {
                        reject(new Error(`HTTP error! status: ${res.statusCode}`));
                    }
                });
            });

            req.on('error', (error) => {
                reject(error);
            });

            req.end();
        });
    }

    // 重写 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 = {}) {
        // 如果message是对象，序列化为JSON字符串
        const finalMessage = typeof message === 'object' ? JSON.stringify(message) : String(message);

        const logData = {
            level: level,
            message: finalMessage,
            timestamp: new Date().toISOString(),
            appName: this.appName,
            userAgent: 'Node.js',
            url: 'Node.js',
            ...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;
}