// Native fetch available in Node 20+

export interface AliyunConfig {
  cookie?: string;
  nickname?: string;
}

export class AliyunDriver {
  private config: AliyunConfig;
  private baseUrl = 'https://api.aliyundrive.com';

  constructor(config: AliyunConfig = {}) {
    this.config = config;
  }

  /**
   * Extract share_id from an Aliyun share URL.
   * Supports:
   *   https://www.aliyundrive.com/s/XXXYYY
   *   https://www.alipan.com/s/XXXYYY
   *   https://api.aliyundrive.com/v2/share_link/XXXYYY
   */
  private extractShareId(shareUrl: string): string | null {
    try {
      const url = new URL(shareUrl);
      const pathMatch = url.pathname.match(/\/s\/([a-zA-Z0-9]+)/);
      if (pathMatch) return pathMatch[1];

      const shareMatch = url.pathname.match(/\/share_link\/([a-zA-Z0-9]+)/);
      if (shareMatch) return shareMatch[1];

      return null;
    } catch {
      return null;
    }
  }

  /**
   * Validate a share link using Aliyun's public anonymous API.
   * No cookie or token required — this endpoint is open.
   * 
   * API:
   *   POST https://api.aliyundrive.com/v2/share_link/get_share_by_anonymous
   *   Body: { "share_id": "XXXYYY", "share_pwd": "" }
   * 
   * Success: returns share_name, file_infos, creator info
   * Failure: returns error code (ShareLinkExpired, ShareLinkCancelled, etc.)
   */
  async validateShareLink(shareUrl: string): Promise<{
    valid: boolean;
    message: string;
    fileCount?: number;
    shareName?: string;
  }> {
    const shareId = this.extractShareId(shareUrl);
    if (!shareId) {
      return { valid: false, message: '无法解析阿里云盘链接格式' };
    }

    try {
      const response = await fetch(
        `${this.baseUrl}/v2/share_link/get_share_by_anonymous`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Referer': 'https://www.aliyundrive.com/',
            'Accept-Language': 'zh-CN,zh;q=0.9',
          },
          body: JSON.stringify({
            share_id: shareId,
            share_pwd: '',
          }),
          signal: AbortSignal.timeout(10000),
        }
      );

      if (!response.ok) {
        return { valid: false, message: `HTTP ${response.status}: API 请求失败` };
      }

      const data = await response.json() as any;

      // Check for error codes
      if (data.code) {
        switch (data.code) {
          case 'ShareLinkExpired':
            return { valid: false, message: '分享已失效（已过期）' };
          case 'ShareLinkCancelled':
            return { valid: false, message: '分享已被取消' };
          case 'NotFound.ShareLink':
            return { valid: false, message: '分享链接不存在' };
          case 'ShareLinkPasswordIncorrect':
            return { valid: true, message: '需要提取码（链接有效）' };
          default:
            return { valid: false, message: data.message || `未知错误 (${data.code})` };
        }
      }

      // Success — valid share link
      const fileInfos = data.file_infos || [];
      return {
        valid: true,
        message: `有效链接（${fileInfos.length} 个文件）`,
        fileCount: fileInfos.length,
        shareName: data.share_name || '',
      };
    } catch (err: any) {
      return { valid: false, message: `网络错误: ${err.message || err}` };
    }
  }
}
