import { TOSClientWrapper, TOSClientConfig } from './tos-client.js';
import * as path from 'path';

// TOS 客户端配置
const TOS_CONFIG: TOSClientConfig = {
  accessKeyId: process.env.TOS_ACCESS_KEY_ID || 'your-access-key-id',
  accessKeySecret: process.env.TOS_ACCESS_KEY_SECRET || 'your-access-key-secret',
  endpoint: process.env.TOS_ENDPOINT || 'tos-cn-beijing.volces.com', // 火山对象存储端点
  region: process.env.TOS_REGION || 'cn-beijing',
  bucketName: process.env.TOS_BUCKET_NAME || 'your-bucket-name',
  selfDomain: process.env.TOS_SELF_DOMAIN || 'your-domain.com', // 自定义域名
  disableSSLWarnings: process.env.TOS_DISABLE_SSL_WARNINGS === 'true' // 通过环境变量控制
};

// 懒加载 TOS 客户端实例
let tosClient: TOSClientWrapper | null = null;

/**
 * 获取TOS客户端实例（懒加载）
 */
function getTOSClient(): TOSClientWrapper {
  if (!tosClient) {
    tosClient = new TOSClientWrapper(TOS_CONFIG);
  }
  return tosClient;
}

// 使用示例
export class TOSService {
  
  /**
   * 上传文本内容
   */
  static async uploadText(content: string, fileName: string): Promise<string> {
    try {
      const objectKey = `text/${Date.now()}-${fileName}`;
      return await getTOSClient().uploadString(content, objectKey);
    } catch (error) {
      console.error('上传文本失败:', error.message);
      throw error;
    }
  }

  /**
   * 上传本地文件
   */
  static async uploadLocalFile(filePath: string, targetPath?: string): Promise<string> {
    try {
      const objectKey = targetPath || `files/${Date.now()}-${path.basename(filePath)}`;
      return await getTOSClient().uploadFile(filePath, objectKey);
    } catch (error) {
      console.error('上传本地文件失败:', error.message);
      throw error;
    }
  }

  /**
   * 从URL上传文件
   */
  static async uploadFromUrl(url: string, targetPath?: string, options?: any): Promise<string> {
    try {
      const fileName = path.basename(new URL(url).pathname) || 'downloaded-file';
      const objectKey = targetPath || `downloads/${Date.now()}-${fileName}`;
      return await getTOSClient().uploadFromUrl(url, objectKey, options);
    } catch (error) {
      console.error('从URL上传文件失败:', error.message);
      throw error;
    }
  }

  /**
   * 上传Buffer数据
   */
  static async uploadBuffer(
    buffer: Buffer, 
    fileName: string, 
    contentType?: string,
    folder: string = 'uploads'
  ): Promise<string> {
    try {
      const objectKey = `${folder}/${Date.now()}-${fileName}`;
      return await getTOSClient().uploadBytes(buffer, objectKey, contentType);
    } catch (error) {
      console.error('上传Buffer失败:', error.message);
      throw error;
    }
  }

  /**
   * 下载文件
   */
  static async downloadFile(objectKey: string): Promise<Buffer> {
    try {
      return await getTOSClient().downloadFile(objectKey);
    } catch (error) {
      console.error('下载文件失败:', error.message);
      throw error;
    }
  }

  /**
   * 删除文件
   */
  static async deleteFile(objectKey: string): Promise<boolean> {
    try {
      return await getTOSClient().deleteFile(objectKey);
    } catch (error) {
      console.error('删除文件失败:', error.message);
      throw error;
    }
  }

  /**
   * 检查文件是否存在
   */
  static async fileExists(objectKey: string): Promise<boolean> {
    try {
      return await getTOSClient().fileExists(objectKey);
    } catch (error) {
      console.error('检查文件存在性失败:', error.message);
      throw error;
    }
  }

  /**
   * 获取文件信息
   */
  static async getFileInfo(objectKey: string): Promise<any> {
    try {
      return await getTOSClient().getFileInfo(objectKey);
    } catch (error) {
      console.error('获取文件信息失败:', error.message);
      throw error;
    }
  }

  /**
   * 生成临时访问URL
   */
  static async generateTempUrl(objectKey: string, expires: number = 3600): Promise<string> {
    try {
      return await getTOSClient().generateUrl(objectKey, expires);
    } catch (error) {
      console.error('生成临时URL失败:', error.message);
      throw error;
    }
  }

  /**
   * 获取公开访问URL
   */
  static getPublicUrl(objectKey: string): string {
    return getTOSClient().getBaseUrl(objectKey);
  }

  /**
   * 列出文件
   */
  static async listFiles(prefix?: string, maxKeys: number = 100): Promise<any[]> {
    try {
      return await getTOSClient().listObjects(prefix, maxKeys);
    } catch (error) {
      console.error('列出文件失败:', error.message);
      throw error;
    }
  }
}

// 导出客户端实例获取函数和服务类
export { getTOSClient as tosClient, TOSClientWrapper };
export default TOSService;

// 使用示例代码
/*
// 1. 上传文本
const textUrl = await TOSService.uploadText('Hello World', 'test.txt');
console.log('文本上传成功:', textUrl);

// 2. 上传本地文件
const fileUrl = await TOSService.uploadLocalFile('/path/to/local/file.jpg');
console.log('文件上传成功:', fileUrl);

// 3. 从URL上传
const urlUploadResult = await TOSService.uploadFromUrl('https://example.com/image.jpg');
console.log('URL上传成功:', urlUploadResult);

// 4. 上传Buffer
const buffer = Buffer.from('Hello Buffer');
const bufferUrl = await TOSService.uploadBuffer(buffer, 'buffer-file.txt', 'text/plain');
console.log('Buffer上传成功:', bufferUrl);

// 5. 下载文件
const downloadedData = await TOSService.downloadFile('uploads/file-key');
console.log('文件下载成功, 大小:', downloadedData.length);

// 6. 检查文件存在性
const exists = await TOSService.fileExists('uploads/file-key');
console.log('文件是否存在:', exists);

// 7. 删除文件
const deleted = await TOSService.deleteFile('uploads/file-key');
console.log('文件删除结果:', deleted);

// 8. 生成临时URL
const tempUrl = await TOSService.generateTempUrl('uploads/file-key', 3600);
console.log('临时URL:', tempUrl);

// 9. 获取公开URL
const publicUrl = TOSService.getPublicUrl('uploads/file-key');
console.log('公开URL:', publicUrl);
*/