import fs from 'fs-extra';
import path from 'path';
import { logger } from './logger.js';

/**
 * 文件操作工具
 */
export class FileUtils {
  /**
   * 确保目录存在
   */
  static async ensureDir(dirPath: string): Promise<void> {
    try {
      await fs.ensureDir(dirPath);
    } catch (error) {
      logger.error(`Failed to create directory: ${dirPath}`);
      throw error;
    }
  }

  /**
   * 复制文件或目录
   */
  static async copy(src: string, dest: string, options?: { overwrite?: boolean }): Promise<void> {
    try {
      const { overwrite = true } = options || {};
      
      if (overwrite && await fs.pathExists(dest)) {
        await fs.remove(dest);
      }
      
      await fs.copy(src, dest);
    } catch (error) {
      logger.error(`Failed to copy ${src} to ${dest}`);
      throw error;
    }
  }

  /**
   * 读取 JSON 文件
   */
  static async readJson<T = any>(filePath: string): Promise<T> {
    try {
      return await fs.readJson(filePath);
    } catch (error) {
      logger.error(`Failed to read JSON file: ${filePath}`);
      throw error;
    }
  }

  /**
   * 写入 JSON 文件
   */
  static async writeJson(filePath: string, data: any, options?: { spaces?: number }): Promise<void> {
    try {
      await fs.ensureDir(path.dirname(filePath));
      await fs.writeJson(filePath, data, { spaces: options?.spaces || 2 });
    } catch (error) {
      logger.error(`Failed to write JSON file: ${filePath}`);
      throw error;
    }
  }

  /**
   * 检查文件或目录是否存在
   */
  static async exists(filePath: string): Promise<boolean> {
    return await fs.pathExists(filePath);
  }

  /**
   * 删除文件或目录
   */
  static async remove(filePath: string): Promise<void> {
    try {
      await fs.remove(filePath);
    } catch (error) {
      logger.error(`Failed to remove: ${filePath}`);
      throw error;
    }
  }

  /**
   * 获取文件扩展名
   */
  static getExtname(filePath: string): string {
    return path.extname(filePath);
  }

  /**
   * 获取文件名（不含扩展名）
   */
  static getBasename(filePath: string): string {
    return path.basename(filePath, path.extname(filePath));
  }

  /**
   * 获取目录名
   */
  static getDirname(filePath: string): string {
    return path.dirname(filePath);
  }

  /**
   * 解析路径
   */
  static resolve(...paths: string[]): string {
    return path.resolve(...paths);
  }

  /**
   * 连接路径
   */
  static join(...paths: string[]): string {
    return path.join(...paths);
  }
}
