import * as vscode from "vscode";
import * as path from "path";

/**
 * 读取文件内容
 */
export async function readFileContent(filePath: string): Promise<string> {
  try {
    // 如果是相对路径，转换为绝对路径
    let absolutePath = filePath;
    if (!path.isAbsolute(filePath)) {
      const workspaceFolders = vscode.workspace.workspaceFolders;
      if (workspaceFolders && workspaceFolders.length > 0) {
        absolutePath = path.join(workspaceFolders[0].uri.fsPath, filePath);
      }
    }

    const fileUri = vscode.Uri.file(absolutePath);

    // 检查文件是否存在并获取文件类型
    try {
      const stat = await vscode.workspace.fs.stat(fileUri);
      if (stat.type !== vscode.FileType.File) {
        throw new Error(`路径不是文件: ${absolutePath}`);
      }
    } catch (error) {
      throw new Error(`文件不存在: ${absolutePath}`);
    }

    // 读取文件内容
    const contentBytes = await vscode.workspace.fs.readFile(fileUri);
    const content = Buffer.from(contentBytes).toString("utf-8");
    return content;
  } catch (error) {
    throw error;
  }
}

/**
 * 读取多个文件内容
 */
export async function readMultipleFiles(
  filePaths: string[]
): Promise<{ path: string; content: string; error?: string }[]> {
  const results = [];

  for (const filePath of filePaths) {
    try {
      const content = await readFileContent(filePath);
      results.push({ path: filePath, content });
    } catch (error) {
      results.push({
        path: filePath,
        content: "",
        error: error instanceof Error ? error.message : "未知错误",
      });
    }
  }

  return results;
}

/**
 * 读取目录下所有文件
 */
export async function readDirectory(
  dirPath: string,
  extensions?: string[]
): Promise<{ path: string; content: string }[]> {
  try {
    // 如果是相对路径，转换为绝对路径
    let absolutePath = dirPath;
    if (!path.isAbsolute(dirPath)) {
      const workspaceFolders = vscode.workspace.workspaceFolders;
      if (workspaceFolders && workspaceFolders.length > 0) {
        absolutePath = path.join(workspaceFolders[0].uri.fsPath, dirPath);
      }
    }

    const dirUri = vscode.Uri.file(absolutePath);

    // 检查目录是否存在
    try {
      const stat = await vscode.workspace.fs.stat(dirUri);
      if (stat.type !== vscode.FileType.Directory) {
        throw new Error(`路径不是目录: ${absolutePath}`);
      }
    } catch (error) {
      throw new Error(`目录不存在: ${absolutePath}`);
    }

    // 读取目录内容
    const entries = await vscode.workspace.fs.readDirectory(dirUri);
    const results = [];

    for (const [fileName, fileType] of entries) {
      // 处理目录
      if (fileType === vscode.FileType.Directory) {
        results.push({ path: fileName + '/', content: '[目录]', isDirectory: true });
        continue;
      }

      // 处理文件
      if (fileType === vscode.FileType.File) {
        // 如果指定了扩展名过滤
        if (extensions && extensions.length > 0) {
          const ext = path.extname(fileName);
          if (!extensions.includes(ext)) {
            continue;
          }
        }

        try {
          const filePath = path.join(absolutePath, fileName);
          const fileUri = vscode.Uri.file(filePath);
          const contentBytes = await vscode.workspace.fs.readFile(fileUri);
          const content = Buffer.from(contentBytes).toString("utf-8");
          results.push({ path: fileName, content, isDirectory: false });
        } catch (error) {
          // 跳过无法读取的文件
          continue;
        }
      }
    }

    return results;
  } catch (error) {
    throw error;
  }
}

/**
 * 获取文件信息
 */
export async function getFileInfo(filePath: string): Promise<{
  exists: boolean;
  isFile: boolean;
  isDirectory: boolean;
  size?: number;
  extension?: string;
}> {
  try {
    let absolutePath = filePath;
    if (!path.isAbsolute(filePath)) {
      const workspaceFolders = vscode.workspace.workspaceFolders;
      if (workspaceFolders && workspaceFolders.length > 0) {
        absolutePath = path.join(workspaceFolders[0].uri.fsPath, filePath);
      }
    }

    const fileUri = vscode.Uri.file(absolutePath);

    try {
      const stat = await vscode.workspace.fs.stat(fileUri);
      return {
        exists: true,
        isFile: stat.type === vscode.FileType.File,
        isDirectory: stat.type === vscode.FileType.Directory,
        size: stat.size,
        extension: path.extname(absolutePath),
      };
    } catch (error) {
      return {
        exists: false,
        isFile: false,
        isDirectory: false,
      };
    }
  } catch (error) {
    return {
      exists: false,
      isFile: false,
      isDirectory: false,
    };
  }
}
