const fs = require('fs');
const path = require('path');
const chalk = require('chalk');

class Logger {
    constructor(logFilePath = null, level = 'INFO') {
        this.logLevels = ['INFO', 'WARN', 'ERROR'];
        this.level = level.toUpperCase(); //不区分大小写 可以偷懒
        this.logFilePath = logFilePath ? path.resolve(logFilePath) : null;

        if (this.logFilePath) {
            // 确保日志目录存在
            const dir = path.dirname(this.logFilePath);
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, { recursive: true });
            }
        }
    }

    log(level, message) {
        level = level.toUpperCase();
        if (this.logLevels.indexOf(level) >= this.logLevels.indexOf(this.level)) {
            const timestamp = new Date().toISOString();
            const logMessage = `${timestamp} [${level}] ${message}`;

            // 控制台颜色
            let coloredMessage;
            switch (level) {
                case 'INFO':
                    coloredMessage = chalk.white(logMessage);
                    break;
                case 'WARN':
                    coloredMessage = chalk.yellow(logMessage);
                    break;
                case 'ERROR':
                    coloredMessage = chalk.red(logMessage);
                    break;
                default:
                    coloredMessage = logMessage;
            }

            console.log(coloredMessage);

            if (this.logFilePath) {
                fs.appendFile(this.logFilePath, `${logMessage}\n`, (err) => {
                    if (err) throw err;
                });
            }
        }
    }

    info(message) {
        this.log('INFO', message);
    }

    warn(message) {
        this.log('WARN', message);
    }

    error(message) {
        this.log('ERROR', message);
    }
}

module.exports = Logger;
