import chalk from 'chalk';
import { LogLevel, LogConfig } from '../types/index.js';

/**
 * 日志工具类
 */
export class Logger {
  private config: LogConfig;

  constructor(config: Partial<LogConfig> = {}) {
    this.config = {
      level: 'info',
      prefix: 'Z-Tools',
      timestamp: true,
      ...config,
    };
  }

  private formatMessage(level: LogLevel, message: string): string {
    const timestamp = this.config.timestamp ? new Date().toISOString() : '';
    const prefix = this.config.prefix ? `[${this.config.prefix}]` : '';
    
    return [timestamp, prefix, message].filter(Boolean).join(' ');
  }

  private shouldLog(level: LogLevel): boolean {
    const levels: LogLevel[] = ['debug', 'info', 'warn', 'error'];
    const currentLevelIndex = levels.indexOf(this.config.level);
    const messageLevelIndex = levels.indexOf(level);
    
    return messageLevelIndex >= currentLevelIndex;
  }

  debug(message: string): void {
    if (this.shouldLog('debug')) {
      console.log(chalk.gray(this.formatMessage('debug', message)));
    }
  }

  info(message: string): void {
    if (this.shouldLog('info')) {
      console.log(chalk.blue(this.formatMessage('info', message)));
    }
  }

  success(message: string): void {
    if (this.shouldLog('info')) {
      console.log(chalk.green(this.formatMessage('info', message)));
    }
  }

  warn(message: string): void {
    if (this.shouldLog('warn')) {
      console.warn(chalk.yellow(this.formatMessage('warn', message)));
    }
  }

  error(message: string): void {
    if (this.shouldLog('error')) {
      console.error(chalk.red(this.formatMessage('error', message)));
    }
  }
}

// 默认日志实例
export const logger = new Logger();
