import { StorageProviderError } from './chunk-ZGVB35L2.mjs';
import { createLogger } from './chunk-KQGP6BTS.mjs';
import { promises, existsSync, createWriteStream, createReadStream } from 'fs';
import * as path from 'path';
import { pipeline } from 'stream/promises';

var logger = createLogger("LocalStorageProvider");
var LocalStorageProvider = class {
  constructor() {
    this.type = "local";
    this.config = null;
    this.isInitialized = false;
  }
  /**
   * 初始化存储提供者
   */
  async initialize(config) {
    if (config.type !== "local") {
      throw new StorageProviderError("\u914D\u7F6E\u7C7B\u578B\u4E0D\u5339\u914D\uFF1A\u671F\u671B local");
    }
    this.config = config;
    logger.info(`\u{1F4C2} [LocalStorageProvider] \u521D\u59CB\u5316\u672C\u5730\u5B58\u50A8\uFF0C\u6839\u76EE\u5F55: ${this.config.rootPath}`);
    try {
      await this.ensureDirectoryExists(this.config.rootPath);
      await this.validateDirectoryAccess(this.config.rootPath);
      this.isInitialized = true;
      logger.info("\u2705 [LocalStorageProvider] \u672C\u5730\u5B58\u50A8\u521D\u59CB\u5316\u5B8C\u6210");
    } catch (error) {
      logger.error("\u274C [LocalStorageProvider] \u672C\u5730\u5B58\u50A8\u521D\u59CB\u5316\u5931\u8D25:", error);
      throw new StorageProviderError(
        `\u672C\u5730\u5B58\u50A8\u521D\u59CB\u5316\u5931\u8D25: ${error instanceof Error ? error.message : "\u672A\u77E5\u9519\u8BEF"}`
      );
    }
  }
  /**
   * 上传文件
   */
  async upload(fileInfo, filePath) {
    this.ensureInitialized();
    const startTime = Date.now();
    logger.info(`\u{1F4E4} [LocalStorageProvider] \u5F00\u59CB\u4E0A\u4F20\u6587\u4EF6: ${filePath}`);
    try {
      const fullPath = this.getFullPath(filePath);
      await this.ensureDirectoryExists(path.dirname(fullPath));
      const buffer = Buffer.from(await fileInfo.file.arrayBuffer());
      await promises.writeFile(fullPath, buffer);
      const stats = await promises.stat(fullPath);
      if (stats.size !== fileInfo.file.size) {
        throw new StorageProviderError(
          `\u6587\u4EF6\u5927\u5C0F\u4E0D\u5339\u914D: \u671F\u671B ${fileInfo.file.size}, \u5B9E\u9645 ${stats.size}`
        );
      }
      const accessUrl = this.generateAccessUrl(filePath);
      const uploadTime = Date.now() - startTime;
      logger.info(`\u2705 [LocalStorageProvider] \u6587\u4EF6\u4E0A\u4F20\u5B8C\u6210: ${filePath}, \u8017\u65F6: ${uploadTime}ms`);
      return {
        success: true,
        path: filePath,
        url: accessUrl,
        size: stats.size,
        data: {
          fullPath,
          uploadTime
        }
      };
    } catch (error) {
      logger.error(`\u274C [LocalStorageProvider] \u6587\u4EF6\u4E0A\u4F20\u5931\u8D25: ${filePath}:`, error);
      return {
        success: false,
        error: error instanceof Error ? error.message : "\u4E0A\u4F20\u5931\u8D25"
      };
    }
  }
  /**
   * 下载文件
   */
  async download(path2) {
    this.ensureInitialized();
    logger.info(`\u{1F4E5} [LocalStorageProvider] \u5F00\u59CB\u4E0B\u8F7D\u6587\u4EF6: ${path2}`);
    try {
      const fullPath = this.getFullPath(path2);
      if (!existsSync(fullPath)) {
        throw new StorageProviderError(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${path2}`);
      }
      const buffer = await promises.readFile(fullPath);
      logger.info(`\u2705 [LocalStorageProvider] \u6587\u4EF6\u4E0B\u8F7D\u5B8C\u6210: ${path2}, \u5927\u5C0F: ${buffer.length}`);
      return buffer;
    } catch (error) {
      logger.error(`\u274C [LocalStorageProvider] \u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25: ${path2}:`, error);
      throw new StorageProviderError(
        `\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25: ${error instanceof Error ? error.message : "\u672A\u77E5\u9519\u8BEF"}`
      );
    }
  }
  /**
   * 删除文件
   */
  async delete(path2) {
    this.ensureInitialized();
    logger.info(`\u{1F5D1}\uFE0F [LocalStorageProvider] \u5F00\u59CB\u5220\u9664\u6587\u4EF6: ${path2}`);
    try {
      const fullPath = this.getFullPath(path2);
      if (!existsSync(fullPath)) {
        logger.warn(`\u26A0\uFE0F [LocalStorageProvider] \u6587\u4EF6\u4E0D\u5B58\u5728: ${path2}`);
        return {
          success: true,
          // 文件不存在也视为删除成功
          data: { reason: "file_not_exists" }
        };
      }
      await promises.unlink(fullPath);
      logger.info(`\u2705 [LocalStorageProvider] \u6587\u4EF6\u5220\u9664\u5B8C\u6210: ${path2}`);
      return {
        success: true,
        data: { deletedPath: fullPath }
      };
    } catch (error) {
      logger.error(`\u274C [LocalStorageProvider] \u6587\u4EF6\u5220\u9664\u5931\u8D25: ${path2}:`, error);
      return {
        success: false,
        error: error instanceof Error ? error.message : "\u5220\u9664\u5931\u8D25"
      };
    }
  }
  /**
   * 获取文件信息
   */
  async getFileInfo(path2) {
    this.ensureInitialized();
    try {
      const fullPath = this.getFullPath(path2);
      if (!existsSync(fullPath)) {
        return {
          success: false,
          error: "\u6587\u4EF6\u4E0D\u5B58\u5728"
        };
      }
      const stats = await promises.stat(fullPath);
      return {
        success: true,
        size: stats.size,
        data: {
          fullPath,
          size: stats.size,
          mtime: stats.mtime,
          ctime: stats.ctime,
          isFile: stats.isFile(),
          isDirectory: stats.isDirectory()
        }
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : "\u83B7\u53D6\u6587\u4EF6\u4FE1\u606F\u5931\u8D25"
      };
    }
  }
  /**
   * 生成访问URL
   */
  async getAccessUrl(path2, _expiresIn) {
    this.ensureInitialized();
    return this.generateAccessUrl(path2);
  }
  /**
   * 生成预签名上传URL
   */
  async getUploadUrl(path2, _expiresIn) {
    this.ensureInitialized();
    logger.warn(`\u26A0\uFE0F [LocalStorageProvider] \u672C\u5730\u5B58\u50A8\u4E0D\u652F\u6301\u9884\u7B7E\u540D\u4E0A\u4F20URL`);
    return this.generateAccessUrl(path2);
  }
  /**
   * 检查文件是否存在
   */
  async exists(path2) {
    this.ensureInitialized();
    try {
      const fullPath = this.getFullPath(path2);
      return existsSync(fullPath);
    } catch {
      return false;
    }
  }
  /**
   * 列出文件
   */
  async list(prefix, maxKeys) {
    this.ensureInitialized();
    try {
      const fullPrefix = this.getFullPath(prefix);
      const baseDir = path.dirname(fullPrefix);
      const filePattern = path.basename(fullPrefix);
      if (!existsSync(baseDir)) {
        return [];
      }
      const entries = await promises.readdir(baseDir, { withFileTypes: true });
      let files = entries.filter((entry) => entry.isFile()).map((entry) => entry.name).filter((name) => name.startsWith(filePattern)).map((name) => path.join(path.dirname(prefix), name));
      if (maxKeys && maxKeys > 0) {
        files = files.slice(0, maxKeys);
      }
      return files;
    } catch (error) {
      logger.error(`\u274C [LocalStorageProvider] \u5217\u51FA\u6587\u4EF6\u5931\u8D25: ${prefix}:`, error);
      return [];
    }
  }
  // ============= 私有方法 =============
  /**
   * 确保已初始化
   */
  ensureInitialized() {
    if (!this.isInitialized || !this.config) {
      throw new StorageProviderError("\u5B58\u50A8\u63D0\u4F9B\u8005\u672A\u521D\u59CB\u5316");
    }
  }
  /**
   * 获取完整文件路径
   */
  getFullPath(relativePath) {
    if (!this.config) {
      throw new StorageProviderError("\u5B58\u50A8\u63D0\u4F9B\u8005\u672A\u521D\u59CB\u5316");
    }
    const normalizedPath = path.normalize(relativePath);
    if (normalizedPath.includes("..")) {
      throw new StorageProviderError("\u975E\u6CD5\u8DEF\u5F84\uFF1A\u4E0D\u5141\u8BB8\u4F7F\u7528\u7236\u76EE\u5F55\u5F15\u7528");
    }
    return path.join(this.config.rootPath, normalizedPath);
  }
  /**
   * 生成访问URL
   */
  generateAccessUrl(relativePath) {
    if (!this.config) {
      throw new StorageProviderError("\u5B58\u50A8\u63D0\u4F9B\u8005\u672A\u521D\u59CB\u5316");
    }
    const urlPath = relativePath.replace(/\\/g, "/");
    const normalizedUrlPath = urlPath.startsWith("/") ? urlPath : `/${urlPath}`;
    return `${this.config.baseUrl}${normalizedUrlPath}`;
  }
  /**
   * 确保目录存在
   */
  async ensureDirectoryExists(dirPath) {
    try {
      await promises.mkdir(dirPath, { recursive: true });
    } catch (error) {
      if (error instanceof Error && "code" in error && error.code !== "EEXIST") {
        throw error;
      }
    }
  }
  /**
   * 验证目录访问权限
   */
  async validateDirectoryAccess(dirPath) {
    try {
      await promises.access(dirPath, promises.constants.R_OK | promises.constants.W_OK);
    } catch (error) {
      throw new StorageProviderError(
        `\u76EE\u5F55\u8BBF\u95EE\u6743\u9650\u4E0D\u8DB3: ${dirPath}, ${error instanceof Error ? error.message : "\u672A\u77E5\u9519\u8BEF"}`
      );
    }
  }
  /**
   * 流式上传大文件（可选实现）
   */
  async uploadStream(readableStream, filePath) {
    this.ensureInitialized();
    const startTime = Date.now();
    logger.info(`\u{1F4E4} [LocalStorageProvider] \u5F00\u59CB\u6D41\u5F0F\u4E0A\u4F20\u6587\u4EF6: ${filePath}`);
    try {
      const fullPath = this.getFullPath(filePath);
      await this.ensureDirectoryExists(path.dirname(fullPath));
      const writeStream = createWriteStream(fullPath);
      await pipeline(readableStream, writeStream);
      const stats = await promises.stat(fullPath);
      const accessUrl = this.generateAccessUrl(filePath);
      const uploadTime = Date.now() - startTime;
      logger.info(
        `\u2705 [LocalStorageProvider] \u6D41\u5F0F\u4E0A\u4F20\u5B8C\u6210: ${filePath}, \u5927\u5C0F: ${stats.size}, \u8017\u65F6: ${uploadTime}ms`
      );
      return {
        success: true,
        path: filePath,
        url: accessUrl,
        size: stats.size,
        data: {
          fullPath,
          uploadTime
        }
      };
    } catch (error) {
      logger.error(`\u274C [LocalStorageProvider] \u6D41\u5F0F\u4E0A\u4F20\u5931\u8D25: ${filePath}:`, error);
      return {
        success: false,
        error: error instanceof Error ? error.message : "\u6D41\u5F0F\u4E0A\u4F20\u5931\u8D25"
      };
    }
  }
  /**
   * 流式下载大文件（可选实现）
   */
  createDownloadStream(path2) {
    this.ensureInitialized();
    const fullPath = this.getFullPath(path2);
    if (!existsSync(fullPath)) {
      throw new StorageProviderError(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${path2}`);
    }
    return createReadStream(fullPath);
  }
};

export { LocalStorageProvider };
//# sourceMappingURL=chunk-GSTLV3MB.mjs.map
//# sourceMappingURL=chunk-GSTLV3MB.mjs.map