// 直接测试文件日志功能
const fs = require('fs/promises');
const path = require('path');

class FileLogger {
  constructor(serviceName, logDir) {
    this.serviceName = serviceName;
    this.logDir = logDir || process.env.LOG_DIR || './log-prd';
  }

  getDateFolderPath() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    return path.join(this.logDir, `${year}-${month}-${day}`);
  }

  getLogFilePath() {
    const dateFolder = this.getDateFolderPath();
    return path.join(dateFolder, `${this.serviceName}.log`);
  }

  async ensureLogDir() {
    const logFilePath = this.getLogFilePath();
    const logDir = path.dirname(logFilePath);

    try {
      await fs.mkdir(logDir, { recursive: true });
    } catch (error) {
      console.error(`创建日志目录失败: ${error}`);
      throw error;
    }
  }

  formatMessage(level, message, metadata) {
    const now = new Date();
    const timestamp = now.toISOString();
    const formattedMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;

    if (metadata) {
      const metadataStr = typeof metadata === 'object'
        ? JSON.stringify(metadata, null, 2)
        : String(metadata);
      return `${formattedMessage}\n${metadataStr}\n`;
    }

    return `${formattedMessage}\n`;
  }

  async writeToFile(level, message, metadata) {
    try {
      await this.ensureLogDir();
      const logFilePath = this.getLogFilePath();
      const formattedMessage = this.formatMessage(level, message, metadata);

      await fs.appendFile(logFilePath, formattedMessage, 'utf8');
      console.log(`日志已写入: ${logFilePath}`);
    } catch (error) {
      console.error(`写入日志文件失败: ${error}`);
      // 不抛出错误，避免影响主流程
    }
  }

  async info(message, metadata) {
    console.log(`[INFO] ${message}`, metadata || '');
    await this.writeToFile('info', message, metadata);
  }

  async warn(message, metadata) {
    console.warn(`[WARN] ${message}`, metadata || '');
    await this.writeToFile('warn', message, metadata);
  }

  async error(message, metadata) {
    console.error(`[ERROR] ${message}`, metadata || '');
    await this.writeToFile('error', message, metadata);
  }

  async debug(message, metadata) {
    console.debug(`[DEBUG] ${message}`, metadata || '');
    await this.writeToFile('debug', message, metadata);
  }
}

function createServiceLogger(serviceName, logDir) {
  return new FileLogger(serviceName, logDir);
}

// 测试函数
async function testDirectLogging() {
  console.log('开始直接测试日志功能...\n');

  // 创建日志器
  const logger = createServiceLogger('feie-print-task-service-direct-test');

  // 测试不同级别的日志
  console.log('1. 测试信息级别日志...');
  await logger.info('测试信息日志', { taskId: 'TEST_123', status: 'PENDING' });

  console.log('2. 测试警告级别日志...');
  await logger.warn('测试警告日志', { error: '打印机未连接', retryCount: 1 });

  console.log('3. 测试错误级别日志...');
  await logger.error('测试错误日志', { error: '打印失败', code: -1 });

  console.log('4. 测试调试级别日志...');
  await logger.debug('测试调试日志', { response: { ret: 0, msg: 'success' } });

  console.log('5. 测试简单消息（无元数据）...');
  await logger.info('简单日志消息');

  console.log('\n直接日志测试完成！');
  console.log('日志文件应该创建在: ./log-prd/YYYY-MM-DD/feie-print-task-service-direct-test.log');

  // 显示日志文件路径
  const logFilePath = logger.getLogFilePath();
  console.log(`完整路径: ${logFilePath}`);

  // 尝试读取并显示日志内容
  try {
    const content = await fs.readFile(logFilePath, 'utf8');
    console.log('\n=== 日志文件内容 ===');
    console.log(content);
    console.log('=== 结束 ===');
  } catch (error) {
    console.log('无法读取日志文件，可能尚未创建或权限问题');
  }
}

// 运行测试
testDirectLogging().catch(error => {
  console.error('测试失败:', error);
  process.exit(1);
});