/// <reference lib="dom" />
import { chromium, type BrowserContext, type Page } from 'playwright';
import { logger } from '../utils/logger.js';
import type { PlatformType } from '@media-manager/shared';

// Python 服务配置
const PYTHON_SERVICE_URL = process.env.PYTHON_PUBLISH_SERVICE_URL || process.env.XHS_SERVICE_URL || 'http://localhost:5005';

// 抖音 API 接口配置
const DOUYIN_API = {
  // 检查用户登录状态 - 返回 result: true 表示已登录（需要在浏览器上下文中调用）
  CHECK_USER: '/aweme/v1/creator/check/user/',
  // 获取作品列表（新接口，支持分页）
  WORK_LIST: 'https://creator.douyin.com/janus/douyin/creator/pc/work_list',
  // 获取评论列表
  COMMENT_LIST: 'https://creator.douyin.com/web/api/third_party/aweme/api/comment/read/aweme/v1/web/comment/list/select/',
  // 创作者首页（用于触发登录检查）
  CREATOR_HOME: 'https://creator.douyin.com/creator-micro/home',
};

// 平台 API 配置（用于直接 HTTP 请求检查）
const PLATFORM_API_CONFIG: Record<string, {
  checkUrl: string;
  isValidResponse: (data: unknown) => boolean;
}> = {
  douyin: {
    // 使用账号基础信息接口检查 Cookie 有效性
    checkUrl: 'https://creator.douyin.com/web/api/creator/mcn/account_base_info?show_mcn_status=1',
    isValidResponse: (data: unknown) => {
      const resp = data as { status_code?: number; BaseResp?: { StatusCode?: number } };
      // status_code 为 0 表示 Cookie 有效
      return resp?.status_code === 0 || resp?.BaseResp?.StatusCode === 0;
    },
  },
  baijiahao: {
    // 使用 appinfo 接口检查 Cookie 有效性
    checkUrl: 'https://baijiahao.baidu.com/builder/app/appinfo',
    isValidResponse: (data: unknown) => {
      const resp = data as {
        errno?: number;
        errmsg?: string;
        data?: {
          user?: {
            name?: string;
            app_id?: string | number;
            userid?: number;
            status?: string;
          }
        }
      };

      logger.info(`[Baijiahao] API response: errno=${resp?.errno}, errmsg=${resp?.errmsg}, user.name=${resp?.data?.user?.name}, user.app_id=${resp?.data?.user?.app_id}, user.status=${resp?.data?.user?.status}`);

      // errno 为 0 表示请求成功
      const isErrnoOk = resp?.errno === 0;

      // 必须有用户信息（name 或 app_id）
      const hasUserInfo = !!(resp?.data?.user?.name || resp?.data?.user?.app_id);

      // 用户状态不能是 'banned' 或其他异常状态
      const userStatus = resp?.data?.user?.status;
      const isStatusOk = !userStatus || userStatus === 'audit' || userStatus === 'pass' || userStatus === 'active';

      const isValid = isErrnoOk && hasUserInfo && isStatusOk;

      if (!isValid) {
        logger.warn(`[Baijiahao] Cookie invalid: errno=${resp?.errno}, hasUserInfo=${hasUserInfo}, status=${userStatus}`);
      }

      return isValid;
    },
  },
};

export interface AccountInfo {
  accountId: string;
  accountName: string;
  avatarUrl: string;
  fansCount: number;
  worksCount: number;
  worksList?: WorkItem[];
}

export interface WorkItem {
  videoId?: string;
  title: string;
  coverUrl: string;
  duration: string;
  publishTime: string;
  status: string;
  playCount: number;
  likeCount: number;
  commentCount: number;
  shareCount: number;
}

export interface CommentItem {
  commentId: string;
  authorId: string;
  authorName: string;
  authorAvatar: string;
  content: string;
  likeCount: number;
  commentTime: string;
  parentCommentId?: string;
  videoId?: string;
  videoTitle?: string;
  videoCoverUrl?: string;
}

export interface WorkComments {
  videoId: string;
  videoTitle: string;
  videoCoverUrl: string;
  comments: CommentItem[];
}

export interface CookieData {
  name: string;
  value: string;
  domain: string;
  path: string;
}

/**
 * 无头浏览器服务 - 用于后台静默获取账号信息
 */
class HeadlessBrowserService {
  /**
   * 检查 Cookie 是否有效
   * 优先使用 Python 服务（通过浏览器访问后台检测），回退到 API 检查
   */
  async checkCookieValid(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
    logger.info(`[checkCookieValid] Checking cookie for ${platform}, cookie count: ${cookies.length}`);

    // 优先使用 Python 服务检查（通过浏览器访问后台页面，检测是否被重定向到登录页）
    const pythonAvailable = await this.checkPythonServiceAvailable();
    if (pythonAvailable) {
      try {
        const result = await this.checkLoginViaPython(platform, cookies);
        logger.info(`[checkCookieValid] Python service result for ${platform}: ${result}`);
        return result;
      } catch (error) {
        logger.warn(`[Python API] Check login failed, falling back to API check:`, error);
      }
    } else {
      logger.info(`[checkCookieValid] Python service not available, using API check`);
    }

    // 回退到 API 检查
    const apiConfig = PLATFORM_API_CONFIG[platform];
    if (apiConfig) {
      const result = await this.checkCookieValidByApi(platform, cookies, apiConfig);
      logger.info(`[checkCookieValid] API check result for ${platform}: ${result}`);
      return result;
    }

    // 其他平台使用浏览器检查
    const result = await this.checkCookieValidByBrowser(platform, cookies);
    logger.info(`[checkCookieValid] Browser check result for ${platform}: ${result}`);
    return result;
  }

  /**
   * 通过 Python 服务检查登录状态（浏览器访问后台页面，检测是否需要登录）
   */
  private async checkLoginViaPython(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
    const pythonUrl = PYTHON_SERVICE_URL;

    // 构建 Cookie 字符串
    const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');

    logger.info(`[Python API] Checking login status for ${platform}`);

    const response = await fetch(`${pythonUrl}/check_login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        platform,
        cookie: cookieString,
      }),
    });

    if (!response.ok) {
      throw new Error(`Python API returned ${response.status}`);
    }

    const result = await response.json() as {
      success: boolean;
      valid: boolean;
      need_login: boolean;
      message?: string;
      error?: string;
    };

    logger.info(`[Python API] Check login result for ${platform}: valid=${result.valid}, need_login=${result.need_login}`);

    if (!result.success) {
      throw new Error(result.error || 'Check login failed');
    }

    return result.valid && !result.need_login;
  }

  /**
   * 通过 API 检查 Cookie 是否有效
   * 注意：API 返回不确定状态时会回退到浏览器检查，避免误判
   */
  private async checkCookieValidByApi(
    platform: PlatformType,
    cookies: CookieData[],
    apiConfig: typeof PLATFORM_API_CONFIG[string]
  ): Promise<boolean> {
    try {
      // 构建 Cookie 字符串（所有 Cookie 拼接）
      const cookieString = cookies
        .map(c => `${c.name}=${c.value}`)
        .join('; ');

      logger.info(`Checking cookie for ${platform}, cookie count: ${cookies.length}`);

      // 发起 API 请求，模拟浏览器请求
      const response = await fetch(apiConfig.checkUrl, {
        method: 'GET',
        headers: {
          'Accept': 'application/json, text/plain, */*',
          'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
          'Cache-Control': 'no-cache',
          'Cookie': cookieString,
          'Pragma': 'no-cache',
          'Referer': this.getPlatformReferer(platform),
          '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',
          'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"Windows"',
          'sec-fetch-dest': 'empty',
          'sec-fetch-mode': 'cors',
          'sec-fetch-site': 'same-origin',
        },
      });

      const data = await response.json();
      logger.info(`[API] Raw response for ${platform}:`, JSON.stringify(data).substring(0, 500));

      const isValid = apiConfig.isValidResponse(data);
      const statusCode = (data as { status_code?: number; errno?: number; ret?: { errno?: number } })?.status_code
        ?? (data as { errno?: number })?.errno
        ?? (data as { ret?: { errno?: number } })?.ret?.errno;

      logger.info(`API check cookie for ${platform}: valid=${isValid}, statusCode=${statusCode}`);

      // 如果 API 明确返回有效，直接返回 true
      if (isValid) {
        return true;
      }

      // API 返回无效时，检查是否是明确的"未登录"状态
      // 抖音: status_code 为 2 或 8 通常表示未登录/登录过期
      // 百家号: errno 为非 0 可能表示未登录，但需要根据具体错误码判断
      const clearlyNotLoggedIn = statusCode === 2 || statusCode === 8;

      if (clearlyNotLoggedIn) {
        logger.info(`[API] Platform ${platform} clearly not logged in (statusCode=${statusCode})`);
        return false;
      }

      // 百家号特殊处理：根据 errno 判断
      if (platform === 'baijiahao') {
        const errno = (data as { errno?: number })?.errno;

        // errno 为 0 表示请求成功，但可能没有用户信息（已在 isValidResponse 中检查）
        if (errno === 0) {
          // 如果 isValid 为 false，说明虽然请求成功但没有用户信息，可能是 Cookie 无效
          if (!isValid) {
            logger.warn(`[API] Baijiahao errno=0 but no user info, cookie may be invalid`);
            return false;
          }
          return true;
        }

        // errno 非 0 表示请求失败，可能是 Cookie 无效
        // 常见错误码：
        // - 110: 未登录
        // - 其他非 0 值：可能是权限问题或其他错误
        logger.warn(`[API] Baijiahao errno=${errno}, cookie is invalid`);
        return false;
      }

      // 不确定的状态（如 status_code=7），回退到浏览器检查
      logger.info(`[API] Uncertain status for ${platform} (statusCode=${statusCode}), falling back to browser check`);
      return this.checkCookieValidByBrowser(platform, cookies);
    } catch (error) {
      logger.error(`API check cookie error for ${platform}:`, error);
      // API 检查失败时，回退到浏览器检查
      return this.checkCookieValidByBrowser(platform, cookies);
    }
  }

  /**
   * 获取平台 Referer
   */
  private getPlatformReferer(platform: PlatformType): string {
    const referers: Record<string, string> = {
      douyin: 'https://creator.douyin.com/',
      bilibili: 'https://member.bilibili.com/',
      kuaishou: 'https://cp.kuaishou.com/',
      baijiahao: 'https://baijiahao.baidu.com/',
    };
    return referers[platform] || '';
  }

  /**
   * 通过浏览器检查 Cookie 是否有效（检查是否被重定向到登录页）
   * 注意：网络错误或服务不可用时返回 true（保持原状态），避免误判为过期
   */
  private async checkCookieValidByBrowser(platform: PlatformType, cookies: CookieData[]): Promise<boolean> {
    // 对于抖音平台，使用 check/user 接口检查
    if (platform === 'douyin') {
      return this.checkDouyinLoginByApi(cookies);
    }

    const browser = await chromium.launch({ headless: true });

    try {
      const context = await browser.newContext({
        viewport: { width: 1920, height: 1080 },
        locale: 'zh-CN',
        timezoneId: 'Asia/Shanghai',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      });

      await context.addCookies(cookies);
      const page = await context.newPage();

      const config = this.getPlatformConfig(platform);

      // 访问平台主页
      await page.goto(config.homeUrl, {
        waitUntil: 'domcontentloaded',
        timeout: 30000,
      });

      await page.waitForTimeout(3000);

      const url = page.url();
      logger.info(`Browser check cookie for ${platform}: URL=${url}`);

      // 检查是否被重定向到登录页
      const isLoginPage = config.loginIndicators.some(indicator => url.includes(indicator));

      await page.close();
      await context.close();
      await browser.close();

      return !isLoginPage;
    } catch (error) {
      logger.error(`Browser check cookie error for ${platform}:`, error);
      await browser.close();
      // 网络错误或服务不可用时返回 true，避免误判为过期
      logger.warn(`[Browser] Check failed due to error, assuming valid to avoid false expiration`);
      return true;
    }
  }

  /**
   * 抖音登录状态检查 - 通过监听 check/user 接口
   * 访问创作者首页，监听 check/user 接口返回的 result 字段判断登录状态
   */
  async checkDouyinLoginByApi(cookies: CookieData[]): Promise<boolean> {
    const browser = await chromium.launch({ headless: true });
    let isLoggedIn = false;
    let checkCompleted = false;

    try {
      const context = await browser.newContext({
        viewport: { width: 1920, height: 1080 },
        locale: 'zh-CN',
        timezoneId: 'Asia/Shanghai',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      });

      await context.addCookies(cookies);
      const page = await context.newPage();

      // 监听 check/user 接口响应
      page.on('response', async (response) => {
        const url = response.url();
        if (url.includes(DOUYIN_API.CHECK_USER)) {
          try {
            const data = await response.json();
            // result: true 表示已登录
            isLoggedIn = data?.result === true && data?.status_code === 0;
            checkCompleted = true;
            logger.info(`[Douyin] check/user API response: result=${data?.result}, status_code=${data?.status_code}, isLoggedIn=${isLoggedIn}`);
          } catch {
            // 忽略解析错误
          }
        }
      });

      // 访问创作者首页，触发 check/user 接口
      await page.goto(DOUYIN_API.CREATOR_HOME, {
        waitUntil: 'domcontentloaded',
        timeout: 30000,
      });

      // 等待接口响应或超时
      const startTime = Date.now();
      while (!checkCompleted && Date.now() - startTime < 10000) {
        await page.waitForTimeout(500);
      }

      // 如果没有收到 check/user 响应，检查 URL 是否被重定向到登录页
      if (!checkCompleted) {
        const currentUrl = page.url();
        isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
        logger.info(`[Douyin] No check/user response, fallback to URL check: ${currentUrl}, isLoggedIn=${isLoggedIn}`);
      }

      await page.close();
      await context.close();
      await browser.close();

      return isLoggedIn;
    } catch (error) {
      logger.error('[Douyin] checkDouyinLoginByApi error:', error);
      try {
        await browser.close();
      } catch { }
      // 网络错误或服务不可用时返回 true，避免误判为过期
      logger.warn(`[Douyin] Check failed due to error, assuming valid to avoid false expiration`);
      return true;
    }
  }

  /**
   * 访问平台后台页面并截图（用于 AI 分析）
   * @param platform 平台类型
   * @param cookies Cookie 数据
   * @returns Base64 编码的截图，失败返回 null
   */
  async capturePageScreenshot(platform: PlatformType, cookies: CookieData[]): Promise<string | null> {
    const browser = await chromium.launch({ headless: true });

    try {
      const context = await browser.newContext({
        viewport: { width: 1920, height: 1080 },
        locale: 'zh-CN',
        timezoneId: 'Asia/Shanghai',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      });

      await context.addCookies(cookies);
      const page = await context.newPage();

      const config = this.getPlatformConfig(platform);

      logger.info(`[Screenshot] Navigating to ${platform} home page: ${config.homeUrl}`);

      // 访问平台主页
      await page.goto(config.homeUrl, {
        waitUntil: 'domcontentloaded',
        timeout: 30000,
      });

      // 等待页面加载
      await page.waitForTimeout(3000);

      const url = page.url();
      logger.info(`[Screenshot] Current URL: ${url}`);

      // 截图
      const screenshotBuffer = await page.screenshot({
        type: 'jpeg',
        quality: 80,
        fullPage: false,
      });

      const base64Screenshot = screenshotBuffer.toString('base64');

      await page.close();
      await context.close();
      await browser.close();

      logger.info(`[Screenshot] Captured screenshot for ${platform}, size: ${Math.round(base64Screenshot.length / 1024)}KB`);

      return base64Screenshot;
    } catch (error) {
      logger.error(`[Screenshot] Failed to capture screenshot for ${platform}:`, error);
      try {
        await browser.close();
      } catch { /* ignore */ }
      return null;
    }
  }

  /**
   * 检查 Python 服务是否可用
   */
  private async checkPythonServiceAvailable(): Promise<boolean> {
    try {
      const response = await fetch(`${PYTHON_SERVICE_URL}/health`, {
        method: 'GET',
        signal: AbortSignal.timeout(3000),
      });
      return response.ok;
    } catch {
      return false;
    }
  }

  /**
   * 通过 Python API 获取作品列表
   */
  private async fetchWorksViaPython(platform: PlatformType, cookies: CookieData[]): Promise<WorkItem[]> {
    logger.info(`[Python API] Fetching works for ${platform} (auto pagination)...`);

    const cookieString = JSON.stringify(cookies);
    const pythonPlatform = platform === 'weixin_video' ? 'weixin' : platform;

    const pageSize = 50;
    const maxPages = 30;
    const allWorks: WorkItem[] = [];
    const seenIds = new Set<string>();

    for (let page = 0; page < maxPages; page++) {
      logger.info(`[Python API] Fetching works page=${page}, page_size=${pageSize} for ${platform}`);

      const response = await fetch(`${PYTHON_SERVICE_URL}/works`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          platform: pythonPlatform,
          cookie: cookieString,
          page,
          page_size: pageSize,
        }),
      });

      if (!response.ok) {
        throw new Error(`Python API returned ${response.status}`);
      }

      const result = await response.json();

      if (!result.success) {
        throw new Error(result.error || 'Failed to get works');
      }

      const pageWorks: WorkItem[] = (result.works || []).map((work: {
        work_id: string;
        title: string;
        cover_url: string;
        duration: number;
        publish_time: string;
        status: string;
        play_count: number;
        like_count: number;
        comment_count: number;
        share_count: number;
        collect_count?: number;
      }) => ({
        videoId: work.work_id,
        title: work.title,
        coverUrl: work.cover_url,
        duration: String(work.duration || 0),
        publishTime: work.publish_time,
        status: work.status || 'published',
        playCount: work.play_count || 0,
        likeCount: work.like_count || 0,
        commentCount: work.comment_count || 0,
        shareCount: work.share_count || 0,
      }));

      let newCount = 0;
      for (const w of pageWorks) {
        const id = w.videoId || `${platform}_${w.title}_${w.publishTime}`;
        if (!seenIds.has(id)) {
          seenIds.add(id);
          allWorks.push(w);
          newCount++;
        }
      }

      logger.info(
        `[Python API] Page ${page} fetched=${pageWorks.length}, new=${newCount}, total=${allWorks.length}, has_more=${!!result.has_more}`
      );

      if (!result.has_more || pageWorks.length === 0 || newCount === 0) {
        break;
      }
    }

    logger.info(`[Python API] Total works fetched for ${platform}: ${allWorks.length}`);
    return allWorks;
  }

  /**
   * 获取账号信息（优先使用 Python API，回退到无头浏览器）
   */
  async fetchAccountInfo(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
    logger.info(`[fetchAccountInfo] Starting for platform: ${platform}`);

    // 百家号：优先走 Python 的 /account_info（包含粉丝数、作品数），避免 Node 直连分散认证问题
    if (platform === 'baijiahao') {
      const pythonAvailable = await this.checkPythonServiceAvailable();
      if (pythonAvailable) {
        logger.info(`[Python API] Service available, fetching account_info for baijiahao`);
        try {
          return await this.fetchAccountInfoViaPython(platform, cookies);
        } catch (error) {
          logger.warn(`[Python API] Failed to fetch account_info for baijiahao, falling back to direct API:`, error);
        }
      } else {
        logger.info(`[Python API] Service not available for baijiahao, falling back to direct API`);
      }

      // Python 不可用或失败时，回退到 Node 直连 API（可能仍会遇到分散认证问题）
      return this.fetchBaijiahaoAccountInfoDirectApi(cookies);
    }

    // 对于支持的平台，尝试使用 Python API 获取作品列表和账号信息
    // 同步作品需要全量：这里会通过 Python /works 自动分页拉取
    const supportedPlatforms: PlatformType[] = ['douyin', 'xiaohongshu', 'kuaishou', 'weixin_video', 'baijiahao'];

    if (supportedPlatforms.includes(platform)) {
      const pythonAvailable = await this.checkPythonServiceAvailable();
      if (pythonAvailable) {
        logger.info(`[Python API] Service available, trying to fetch works for ${platform}`);
        try {
          const worksList = await this.fetchWorksViaPython(platform, cookies);

          // 如果成功获取到作品，使用 Playwright 获取账号基本信息
          if (worksList.length > 0) {
            logger.info(`[Python API] Successfully fetched ${worksList.length} works for ${platform}`);

            try {
              const accountInfo = await this.fetchAccountInfoWithPlaywright(platform, cookies);
              accountInfo.worksList = worksList;
              // 直接使用 Python API 获取的作品数量（最准确，排除了已删除/私密视频）
              accountInfo.worksCount = worksList.length;
              logger.info(`[fetchAccountInfo] Using Python API works count for ${platform}: ${accountInfo.worksCount}`);
              return accountInfo;
            } catch (playwrightError) {
              logger.warn(`[Playwright] Failed to get account info for ${platform}:`, playwrightError);
              const accountInfo = this.getDefaultAccountInfo(platform);
              accountInfo.worksList = worksList;
              accountInfo.worksCount = worksList.length;
              return accountInfo;
            }
          }

          // 作品列表为空，尝试用 Playwright 获取账号信息
          logger.info(`[Python API] Got empty works list for ${platform}, trying Playwright`);
        } catch (pythonError) {
          logger.warn(`[Python API] Failed to fetch works for ${platform}:`, pythonError);
        }
      } else {
        logger.info(`[Python API] Service not available for ${platform}`);
      }
    }

    // 使用 Playwright 获取账号信息
    logger.info(`[Playwright] Fetching account info for ${platform}`);
    return this.fetchAccountInfoWithPlaywright(platform, cookies);
  }

  /**
   * 使用 Playwright 获取账号信息（原方法）
   */
  private async fetchAccountInfoWithPlaywright(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
    const browser = await chromium.launch({ headless: true });

    try {
      const context = await browser.newContext({
        viewport: { width: 1920, height: 1080 },
        locale: 'zh-CN',
        timezoneId: 'Asia/Shanghai',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      });

      await context.addCookies(cookies);
      const page = await context.newPage();

      let accountInfo: AccountInfo;

      switch (platform) {
        case 'douyin':
          accountInfo = await this.fetchDouyinAccountInfo(page, context, cookies);
          break;
        case 'bilibili':
          accountInfo = await this.fetchBilibiliAccountInfo(page, context, cookies);
          break;
        case 'kuaishou':
          accountInfo = await this.fetchKuaishouAccountInfo(page, context, cookies);
          break;
        case 'xiaohongshu':
          accountInfo = await this.fetchXiaohongshuAccountInfo(page, context, cookies);
          break;
        case 'weixin_video':
          accountInfo = await this.fetchWeixinVideoAccountInfo(page, context, cookies);
          break;
        default:
          accountInfo = this.getDefaultAccountInfo(platform);
      }

      await page.close();
      await context.close();
      await browser.close();

      return accountInfo;
    } catch (error) {
      logger.error('HeadlessBrowser fetchAccountInfo error:', error);
      await browser.close();
      return this.getDefaultAccountInfo(platform);
    }
  }

  /**
   * 获取抖音账号信息 - 通过 API 方式获取
   * 1. 监听 check/user 接口验证登录状态
   * 2. 通过 work_list API 获取作品数和作品列表
   */
  private async fetchDouyinAccountInfo(
    page: Page,
    _context: BrowserContext,
    cookies: CookieData[]
  ): Promise<AccountInfo> {
    let accountId = `douyin_${Date.now()}`;
    let accountName = '抖音账号';
    let avatarUrl = '';
    let fansCount = 0;
    let worksCount = 0;
    let worksList: WorkItem[] = [];
    let isLoggedIn = false;

    // 用于存储从 API 捕获的数据
    const capturedData: {
      userInfo?: {
        nickname?: string;
        avatar?: string;
        uid?: string;
        sec_uid?: string;
        unique_id?: string;  // 抖音号（如 Ethanfly9392）
        short_id?: string;   // 短ID
        follower_count?: number;
      };
      worksList?: Array<{
        awemeId: string;
        title: string;
        coverUrl: string;
        duration: number;
        createTime: number;
        statistics: { play_count: number; digg_count: number; comment_count: number; share_count: number };
      }>;
      total?: number;
    } = {};

    try {
      // 从 Cookie 获取用户 ID
      const uidCookie = cookies.find(c =>
        ['passport_uid', 'uid', 'ssid'].includes(c.name)
      );
      if (uidCookie?.value) {
        accountId = `douyin_${uidCookie.value}`;
      }

      // 设置 API 响应监听器
      page.on('response', async (response) => {
        const url = response.url();
        try {
          // 监听 check/user 接口 - 验证登录状态
          if (url.includes(DOUYIN_API.CHECK_USER)) {
            const data = await response.json();
            isLoggedIn = data?.result === true && data?.status_code === 0;
            logger.info(`[Douyin API] check/user: isLoggedIn=${isLoggedIn}`);
          }

          // 监听 work_list 接口 - 获取作品列表
          if (url.includes('/work_list') || url.includes('/janus/douyin/creator/pc/work_list')) {
            const data = await response.json();
            if (data?.aweme_list && data.aweme_list.length > 0) {
              // 优先从 author.aweme_count 获取真实的作品数（最准确）
              const firstAweme = data.aweme_list[0];
              const authorAwemeCount = firstAweme?.author?.aweme_count;
              if (authorAwemeCount !== undefined && authorAwemeCount > 0) {
                capturedData.total = authorAwemeCount;
                logger.info(`[Douyin API] Using author.aweme_count as works count: ${authorAwemeCount}`);
              } else {
                // 备用方案：使用 items 数组长度
                const itemsCount = data?.items?.length || 0;
                if (itemsCount > 0) {
                  capturedData.total = (capturedData.total || 0) + itemsCount;
                } else {
                  // 如果没有 items，使用 aweme_list 长度
                  capturedData.total = (capturedData.total || 0) + data.aweme_list.length;
                }
              }
              // 解析作品列表
              capturedData.worksList = data.aweme_list.map((aweme: Record<string, unknown>) => {
                const statistics = aweme.statistics as Record<string, unknown> || {};
                const cover = aweme.Cover as { url_list?: string[] } || aweme.video as { cover?: { url_list?: string[] } };
                const coverUrl = cover?.url_list?.[0] || (cover as { cover?: { url_list?: string[] } })?.cover?.url_list?.[0] || '';

                return {
                  awemeId: String(aweme.aweme_id || ''),
                  title: String(aweme.item_title || aweme.desc || '').split('\n')[0].slice(0, 50) || '无标题',
                  coverUrl,
                  duration: Number(aweme.duration || 0),
                  createTime: Number(aweme.create_time || 0),
                  statistics: {
                    play_count: Number(statistics.play_count || 0),
                    digg_count: Number(statistics.digg_count || 0),
                    comment_count: Number(statistics.comment_count || 0),
                    share_count: Number(statistics.share_count || 0),
                  },
                };
              });
              logger.info(`[Douyin API] work_list: itemsCount=${capturedData.total}, aweme_list_length=${capturedData.worksList?.length}`);
            }
          }

          // 监听账号信息接口 - 增加更多可能的接口
          if (url.includes('/account_base_info') ||
            url.includes('/user/info') ||
            url.includes('/creator/user') ||
            url.includes('/data/overview') ||
            url.includes('/creator-micro/data') ||
            url.includes('/home_data')) {
            const data = await response.json();
            logger.info(`[Douyin API] Captured response from: ${url.split('?')[0]}`);

            // 尝试多种数据结构
            const user = data?.user || data?.data?.user || data?.data || data;
            if (user) {
              const nickname = user.nickname || user.name || user.nick_name || user.user_name;
              const avatar = user.avatar_url || user.avatar_thumb?.url_list?.[0] || user.avatar || user.avatar_larger?.url_list?.[0];
              const uid = user.uid || user.user_id || user.id;
              const fans = user.follower_count || user.fans_count || user.mplatform_followers_count;
              // 获取抖音号（unique_id 或 short_id）
              const uniqueId = user.unique_id || user.short_id || user.douyin_id;

              if (nickname || uid || uniqueId) {
                capturedData.userInfo = {
                  nickname: nickname,
                  avatar: avatar,
                  uid: uid,
                  sec_uid: user.sec_uid,
                  unique_id: uniqueId,
                  short_id: user.short_id,
                  follower_count: fans,
                };
                logger.info(`[Douyin API] user info captured: nickname=${capturedData.userInfo.nickname}, uid=${capturedData.userInfo.uid}, unique_id=${capturedData.userInfo.unique_id}`);
              }
            }
          }
        } catch (e) {
          // 忽略非 JSON 响应
        }
      });

      // 访问主页获取基本信息并触发 check/user 接口
      logger.info('[Douyin] Navigating to creator home...');
      await page.goto(DOUYIN_API.CREATOR_HOME, {
        waitUntil: 'domcontentloaded',
        timeout: 30000,
      });

      // 等待页面加载完成
      await page.waitForTimeout(3000);

      // 尝试等待网络空闲
      try {
        await page.waitForLoadState('networkidle', { timeout: 10000 });
      } catch {
        // 超时继续
      }

      // 额外等待确保 API 响应被捕获
      await page.waitForTimeout(2000);

      // 检查登录状态 - 如果没有从 API 获取到，通过 URL 判断
      if (!isLoggedIn) {
        const currentUrl = page.url();
        isLoggedIn = !currentUrl.includes('login') && !currentUrl.includes('passport');
      }

      if (!isLoggedIn) {
        logger.warn('[Douyin] Not logged in, returning default account info');
        return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
      }

      // 从页面提取基本账号信息（作为 API 数据的补充）
      const accountData = await page.evaluate(() => {
        const result: { name?: string; avatar?: string; fans?: number; douyinId?: string } = {};

        // 提取抖音号 - 多种方式
        // 方式1：通过选择器查找包含抖音号的元素
        const uniqueIdSelectors = [
          'div[class*="unique"]',
          'span[class*="unique"]',
          'div[class*="douyin-id"]',
          'span[class*="douyin-id"]',
          '[class*="account-id"]',
          '[class*="shortId"]',
          '[class*="short-id"]',
        ];
        for (const selector of uniqueIdSelectors) {
          const el = document.querySelector(selector);
          if (el) {
            const text = el.textContent?.trim() || '';
            const match = text.match(/抖音号[：:]\s*(\S+)/) || text.match(/ID[：:]\s*(\S+)/);
            if (match) {
              result.douyinId = match[1];
              break;
            }
            // 如果元素文本本身就是抖音号（无前缀）
            if (text && !text.includes('抖音号') && /^[a-zA-Z0-9_]+$/.test(text)) {
              result.douyinId = text;
              break;
            }
          }
        }

        // 方式2：全局搜索包含"抖音号"的文本
        if (!result.douyinId) {
          const allElements = Array.from(document.querySelectorAll('span, div, p'));
          for (const el of allElements) {
            const text = el.textContent?.trim() || '';
            // 匹配 "抖音号：xxx" 或 "抖音号: xxx"
            const match = text.match(/抖音号[：:]\s*([a-zA-Z0-9_]+)/);
            if (match && match[1]) {
              result.douyinId = match[1];
              break;
            }
          }
        }

        // 查找头像 - 优先使用头像容器
        const avatarSelectors = [
          '[class*="avatar"] img',
          '[class*="user-avatar"] img',
          '[class*="profile"] img',
          'img[class*="avatar"]',
        ];
        for (const selector of avatarSelectors) {
          const img = document.querySelector(selector) as HTMLImageElement;
          if (img?.src && (img.src.includes('aweme') || img.src.includes('douyinpic') || img.src.includes('bytedance'))) {
            result.avatar = img.src;
            break;
          }
        }

        // 备用方案：查找所有图片
        if (!result.avatar) {
          const avatarImgs = Array.from(document.querySelectorAll('img'));
          for (const img of avatarImgs) {
            const src = img.src || img.getAttribute('src') || '';
            if (src && (src.includes('aweme') || src.includes('douyinpic') || src.includes('bytedance'))) {
              const rect = img.getBoundingClientRect();
              if (rect.width > 30 && rect.width < 150 && rect.top < 300) {
                result.avatar = src;
                break;
              }
            }
          }
        }

        // 获取粉丝数 - 多种选择器
        const fansSelectors = [
          '#guide_home_fans',
          '[class*="fans"]',
          '[class*="follower"]',
          '[class*="data-item"]',
        ];
        for (const selector of fansSelectors) {
          const el = document.querySelector(selector);
          if (el) {
            const text = el.textContent?.trim() || '';
            // 匹配 "123" 或 "1.2万" 或 "粉丝 123"
            const match = text.match(/(\d+(?:\.\d+)?)\s*([万wW])?/);
            if (match) {
              let num = parseFloat(match[1]);
              if (match[2]) num *= 10000;
              result.fans = Math.floor(num);
              break;
            }
          }
        }

        // 查找用户名 - 更精确的选择器
        const nameSelectors = [
          '[class*="user-name"]',
          '[class*="nickname"]',
          '[class*="author-name"]',
          '[class*="profile-name"]',
          'h1[class*="name"]',
          'h2[class*="name"]',
        ];

        for (const selector of nameSelectors) {
          const el = document.querySelector(selector);
          if (el) {
            const text = el.textContent?.trim() || '';
            if (text && text.length >= 2 && text.length <= 30) {
              result.name = text;
              break;
            }
          }
        }

        // 备用方案：查找包含名字的容器
        if (!result.name) {
          const nameContainers = Array.from(document.querySelectorAll('[class*="name"], [class*="nick"], [class*="user"]'));
          for (const container of nameContainers) {
            const text = container.textContent?.trim() || '';
            if (text &&
              text.length >= 2 &&
              text.length <= 20 &&
              !text.includes('关注') &&
              !text.includes('粉丝') &&
              !text.includes('获赞') &&
              !text.includes('加载') &&
              !text.includes('创作') &&
              !text.includes('发布') &&
              !text.includes('抖音号') &&
              !text.match(/^\d+$/)) {
              const rect = container.getBoundingClientRect();
              if (rect.top < 400 && rect.left < 500) {
                result.name = text;
                break;
              }
            }
          }
        }

        return result;
      });

      // 优先使用抖音号作为 ID（unique_id），其次是页面提取的抖音号，最后是 uid
      if (capturedData.userInfo?.unique_id) {
        // 优先使用抖音号（如 Ethanfly9392）
        accountId = `douyin_${capturedData.userInfo.unique_id}`;
        logger.info(`[Douyin] Using unique_id as accountId: ${accountId}`);
      } else if (capturedData.userInfo?.short_id) {
        // 其次使用短ID
        accountId = `douyin_${capturedData.userInfo.short_id}`;
        logger.info(`[Douyin] Using short_id as accountId: ${accountId}`);
      } else if (accountData.douyinId) {
        // 使用页面提取的抖音号
        accountId = `douyin_${accountData.douyinId}`;
        logger.info(`[Douyin] Using page douyinId as accountId: ${accountId}`);
      } else if (capturedData.userInfo?.uid) {
        // 最后使用内部uid
        accountId = `douyin_${capturedData.userInfo.uid}`;
        logger.info(`[Douyin] Using uid as accountId: ${accountId}`);
      }

      accountName = capturedData.userInfo?.nickname || accountData.name || accountName;
      avatarUrl = capturedData.userInfo?.avatar || accountData.avatar || avatarUrl;
      fansCount = capturedData.userInfo?.follower_count || accountData.fans || fansCount;

      // 通过 API 获取作品列表
      logger.info('[Douyin] Fetching works via API...');
      const apiResult = await this.fetchWorksDirectApi(page);

      if (apiResult.works.length > 0) {
        // 使用 items 累计数量作为作品数（apiResult.total 现在是累计的 items.length）
        // 如果 total 为 0，则使用 works 列表长度
        worksCount = apiResult.total > 0 ? apiResult.total : apiResult.works.length;
        worksList = apiResult.works.map(w => ({
          videoId: w.awemeId,
          title: w.title,
          coverUrl: w.coverUrl,
          duration: '00:00',
          publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
          status: 'published',
          playCount: 0,
          likeCount: 0,
          commentCount: w.commentCount,
          shareCount: 0,
        }));
        logger.info(`[Douyin] Got ${apiResult.works.length} works from API, total count: ${worksCount}`);
      } else if (capturedData.worksList && capturedData.worksList.length > 0) {
        // 如果直接 API 调用失败，使用监听到的数据
        worksCount = capturedData.total || capturedData.worksList.length;
        worksList = capturedData.worksList.map(w => ({
          videoId: w.awemeId,
          title: w.title,
          coverUrl: w.coverUrl,
          duration: this.formatDuration(w.duration),
          publishTime: w.createTime ? new Date(w.createTime * 1000).toISOString() : '',
          status: 'published',
          playCount: w.statistics.play_count,
          likeCount: w.statistics.digg_count,
          commentCount: w.statistics.comment_count,
          shareCount: w.statistics.share_count,
        }));
        logger.info(`[Douyin] Got ${worksCount} works from intercepted API data`);
      }

    } catch (error) {
      logger.warn('Failed to fetch Douyin account info:', error);
    }

    return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
  }

  /**
   * 格式化视频时长
   */
  private formatDuration(ms: number): string {
    if (!ms) return '00:00';
    const seconds = Math.floor(ms / 1000);
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  }

  /**
   * 获取B站账号信息
   */
  private async fetchBilibiliAccountInfo(
    page: Page,
    _context: BrowserContext,
    cookies: CookieData[]
  ): Promise<AccountInfo> {
    let accountId = `bilibili_${Date.now()}`;
    let accountName = 'B站账号';
    let avatarUrl = '';
    let fansCount = 0;
    let worksCount = 0;

    try {
      const uidCookie = cookies.find(c => c.name === 'DedeUserID');
      if (uidCookie?.value) {
        accountId = `bilibili_${uidCookie.value}`;
      }

      await page.goto('https://member.bilibili.com/platform/home', {
        waitUntil: 'domcontentloaded',
        timeout: 30000,
      });

      await page.waitForTimeout(3000);

      // 获取用户名
      const nameEl = await page.$('[class*="nickname"], .user-name, .uname');
      if (nameEl) {
        const text = await nameEl.textContent();
        if (text?.trim()) {
          accountName = text.trim();
        }
      }

      // 获取头像
      const avatarEl = await page.$('[class*="avatar"] img, .user-face img');
      if (avatarEl) {
        const src = await avatarEl.getAttribute('src');
        if (src) {
          avatarUrl = src;
        }
      }
    } catch (error) {
      logger.warn('Failed to fetch Bilibili account info:', error);
    }

    return { accountId, accountName, avatarUrl, fansCount, worksCount };
  }

  /**
   * 获取快手账号信息
   */
  private async fetchKuaishouAccountInfo(
    page: Page,
    _context: BrowserContext,
    cookies: CookieData[]
  ): Promise<AccountInfo> {
    let accountId = `kuaishou_${Date.now()}`;
    let accountName = '快手账号';
    let avatarUrl = '';
    let fansCount = 0;
    let worksCount = 0;

    try {
      const uidCookie = cookies.find(c => c.name === 'userId' || c.name === 'kuaishou.server.web_st');
      if (uidCookie?.value) {
        accountId = `kuaishou_${uidCookie.value.slice(0, 20)}`;
      }

      await page.goto('https://cp.kuaishou.com/profile', {
        waitUntil: 'domcontentloaded',
        timeout: 30000,
      });

      await page.waitForTimeout(3000);

      // 获取用户名
      const nameEl = await page.$('[class*="nickname"], [class*="userName"]');
      if (nameEl) {
        const text = await nameEl.textContent();
        if (text?.trim()) {
          accountName = text.trim();
        }
      }

      // 获取头像
      const avatarEl = await page.$('[class*="avatar"] img');
      if (avatarEl) {
        const src = await avatarEl.getAttribute('src');
        if (src) {
          avatarUrl = src;
        }
      }
    } catch (error) {
      logger.warn('Failed to fetch Kuaishou account info:', error);
    }

    return { accountId, accountName, avatarUrl, fansCount, worksCount };
  }

  /**
   * 获取微信视频号账号信息
   */
  private async fetchWeixinVideoAccountInfo(
    page: Page,
    _context: BrowserContext,
    cookies: CookieData[]
  ): Promise<AccountInfo> {
    let accountId = `weixin_video_${Date.now()}`;
    let accountName = '视频号账号';
    let avatarUrl = '';
    let fansCount = 0;
    let worksCount = 0;
    let finderId = '';

    try {
      // 从 Cookie 中提取用户标识
      // 优先使用 finder_username（视频号唯一标识）
      const finderUsernameCookie = cookies.find(c => c.name === 'finder_username');
      if (finderUsernameCookie?.value) {
        finderId = finderUsernameCookie.value;
        accountId = `weixin_video_${finderId}`;
        logger.info(`[WeixinVideo] Found finder_username from cookie: ${finderId}`);
      }

      // 备选：使用 wxuin 或 uin
      if (!finderId) {
        const uinCookie = cookies.find(c => c.name === 'wxuin' || c.name === 'uin');
        if (uinCookie?.value) {
          // 仍然保持时间戳格式，后续会尝试从页面获取真实 ID
          accountId = `weixin_video_${uinCookie.value}`;
          logger.info(`[WeixinVideo] Using uin from cookie: ${uinCookie.value}`);
        }
      }

      // 访问视频号创作者平台首页
      await page.goto('https://channels.weixin.qq.com/platform/home', {
        waitUntil: 'domcontentloaded',
        timeout: 30000,
      });

      await page.waitForTimeout(3000);

      // 检查是否需要登录
      const currentUrl = page.url();
      if (currentUrl.includes('login') || currentUrl.includes('passport')) {
        logger.warn('[WeixinVideo] Cookie expired, needs login');
        return { accountId, accountName, avatarUrl, fansCount, worksCount };
      }

      // 从页面提取账号信息
      const accountData = await page.evaluate(() => {
        const result: { name?: string; avatar?: string; fans?: number; works?: number; finderId?: string } = {};

        try {
          // ===== 1. 优先使用精确选择器获取视频号 ID =====
          // 方法1: 通过 #finder-uid-copy 的 data-clipboard-text 属性获取
          const finderIdCopyEl = document.querySelector('#finder-uid-copy');
          if (finderIdCopyEl) {
            const clipboardText = finderIdCopyEl.getAttribute('data-clipboard-text');
            if (clipboardText && clipboardText.length >= 10) {
              result.finderId = clipboardText;
              console.log('[WeixinVideo] Found finder ID from data-clipboard-text:', result.finderId);
            } else {
              // 备选：获取元素文本内容
              const text = finderIdCopyEl.textContent?.trim();
              if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10) {
                result.finderId = text;
                console.log('[WeixinVideo] Found finder ID from #finder-uid-copy text:', result.finderId);
              }
            }
          }

          // 方法2: 通过 .finder-uniq-id 选择器获取
          if (!result.finderId) {
            const finderUniqIdEl = document.querySelector('.finder-uniq-id');
            if (finderUniqIdEl) {
              const clipboardText = finderUniqIdEl.getAttribute('data-clipboard-text');
              if (clipboardText && clipboardText.length >= 10) {
                result.finderId = clipboardText;
                console.log('[WeixinVideo] Found finder ID from .finder-uniq-id data-clipboard-text:', result.finderId);
              } else {
                const text = finderUniqIdEl.textContent?.trim();
                if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10) {
                  result.finderId = text;
                  console.log('[WeixinVideo] Found finder ID from .finder-uniq-id text:', result.finderId);
                }
              }
            }
          }

          // 方法3: 从页面文本中正则匹配
          if (!result.finderId) {
            const bodyText = document.body.innerText || '';
            const finderIdPatterns = [
              /视频号ID[：:\s]*([a-zA-Z0-9_]+)/,
              /视频号[：:\s]*ID[：:\s]*([a-zA-Z0-9_]+)/,
            ];
            for (const pattern of finderIdPatterns) {
              const match = bodyText.match(pattern);
              if (match && match[1] && match[1].length >= 10) {
                result.finderId = match[1];
                console.log('[WeixinVideo] Found finder ID from regex:', result.finderId);
                break;
              }
            }
          }

          // ===== 2. 获取账号名称 =====
          // 优先使用 h2.finder-nickname
          const nicknameEl = document.querySelector('h2.finder-nickname') ||
            document.querySelector('.finder-nickname');
          if (nicknameEl) {
            const text = nicknameEl.textContent?.trim();
            if (text && text.length >= 2 && text.length <= 30) {
              result.name = text;
              console.log('[WeixinVideo] Found name from .finder-nickname:', result.name);
            }
          }

          // 备选选择器
          if (!result.name) {
            const nameSelectors = [
              '.account-name',
              '[class*="nickname"]',
              '[class*="userName"]',
            ];
            for (const selector of nameSelectors) {
              const el = document.querySelector(selector);
              const text = el?.textContent?.trim();
              if (text && text.length >= 2 && text.length <= 30) {
                result.name = text;
                console.log('[WeixinVideo] Found name from selector:', selector, result.name);
                break;
              }
            }
          }

          // ===== 3. 获取头像 =====
          // 优先使用 img.avatar
          const avatarEl = document.querySelector('img.avatar') as HTMLImageElement;
          if (avatarEl?.src && avatarEl.src.startsWith('http')) {
            result.avatar = avatarEl.src;
            console.log('[WeixinVideo] Found avatar from img.avatar:', result.avatar);
          }

          // 备选选择器
          if (!result.avatar) {
            const avatarSelectors = [
              '.finder-info-container img.avatar',
              'img[alt="视频号头像"]',
              'img[src*="wx.qlogo.cn/finderhead"]',
              'img[src*="wx.qlogo"]',
            ];
            for (const selector of avatarSelectors) {
              const el = document.querySelector(selector) as HTMLImageElement;
              if (el?.src && el.src.startsWith('http')) {
                result.avatar = el.src;
                console.log('[WeixinVideo] Found avatar from selector:', selector);
                break;
              }
            }
          }

          // ===== 4. 获取视频数和关注者数 =====
          // 使用 .finder-content-info 中的 .finder-info-num
          const contentInfo = document.querySelector('.finder-content-info');
          if (contentInfo) {
            const infoDivs = contentInfo.querySelectorAll('div');
            infoDivs.forEach(div => {
              const text = div.textContent || '';
              const numEl = div.querySelector('.finder-info-num');
              if (numEl) {
                const num = parseInt(numEl.textContent?.trim() || '0', 10);
                if (text.includes('视频') || text.includes('作品')) {
                  result.works = num;
                  console.log('[WeixinVideo] Found works from .finder-info-num:', result.works);
                } else if (text.includes('关注者') || text.includes('粉丝')) {
                  result.fans = num;
                  console.log('[WeixinVideo] Found fans from .finder-info-num:', result.fans);
                }
              }
            });
          }

          // 备选：从页面整体文本中匹配
          if (result.fans === undefined || result.works === undefined) {
            const bodyText = document.body.innerText || '';

            if (result.fans === undefined) {
              const fansMatch = bodyText.match(/关注者\s*(\d+(?:\.\d+)?[万wW]?)/) ||
                bodyText.match(/粉丝\s*(\d+(?:\.\d+)?[万wW]?)/);
              if (fansMatch) {
                let count = parseFloat(fansMatch[1]);
                if (fansMatch[1].includes('万') || fansMatch[1].toLowerCase().includes('w')) {
                  count = count * 10000;
                }
                result.fans = Math.floor(count);
                console.log('[WeixinVideo] Found fans from text:', result.fans);
              }
            }

            if (result.works === undefined) {
              const worksMatch = bodyText.match(/视频\s*(\d+)/) ||
                bodyText.match(/作品\s*(\d+)/);
              if (worksMatch) {
                result.works = parseInt(worksMatch[1], 10);
                console.log('[WeixinVideo] Found works from text:', result.works);
              }
            }
          }

        } catch (e) {
          console.error('[WeixinVideo] Extract error:', e);
        }

        return result;
      });

      logger.info(`[WeixinVideo] Extracted account data from home page:`, accountData);

      // 更新账号信息
      if (accountData.name) {
        accountName = accountData.name;
      }
      if (accountData.avatar) {
        avatarUrl = accountData.avatar;
      }
      if (accountData.fans !== undefined) {
        fansCount = accountData.fans;
      }
      if (accountData.works !== undefined) {
        worksCount = accountData.works;
      }
      if (accountData.finderId) {
        finderId = accountData.finderId;
        accountId = `weixin_video_${accountData.finderId}`;
      }

      // 如果首页没有获取到视频号 ID，尝试访问账号设置页面
      if (!finderId || finderId.length < 10) {
        logger.info('[WeixinVideo] Finder ID not found on home page, trying account settings page...');

        try {
          // 访问账号设置页面
          await page.goto('https://channels.weixin.qq.com/platform/account', {
            waitUntil: 'domcontentloaded',
            timeout: 30000,
          });
          await page.waitForTimeout(2000);

          // 从账号设置页面提取视频号 ID
          const settingsData = await page.evaluate(() => {
            const result: { finderId?: string; name?: string } = {};
            const bodyText = document.body.innerText || '';

            // 尝试多种匹配模式
            const patterns = [
              /视频号ID[：:\s]*([a-zA-Z0-9_]+)/,
              /视频号[：:\s]*ID[：:\s]*([a-zA-Z0-9_]+)/,
              /视频号[：:\s]+([a-zA-Z0-9_]{10,})/,
              /Finder\s*ID[：:\s]*([a-zA-Z0-9_]+)/i,
              /finder_username[：:\s]*([a-zA-Z0-9_]+)/i,
              /唯一标识[：:\s]*([a-zA-Z0-9_]+)/,
            ];

            for (const pattern of patterns) {
              const match = bodyText.match(pattern);
              if (match && match[1]) {
                result.finderId = match[1];
                console.log('[WeixinVideo] Found finder ID from settings page:', result.finderId);
                break;
              }
            }

            // 从元素中查找
            if (!result.finderId) {
              const idSelectors = [
                '[class*="finder-id"]',
                '[class*="account-id"]',
                '[class*="unique-id"]',
                '.finder-uniq-id',
                'span.finder-uniq-id',
                '[class*="copy-id"]',
              ];
              for (const selector of idSelectors) {
                const el = document.querySelector(selector);
                const text = el?.textContent?.trim();
                if (text && /^[a-zA-Z0-9_]+$/.test(text) && text.length >= 10 && text.length <= 30) {
                  result.finderId = text;
                  console.log('[WeixinVideo] Found ID from settings selector:', result.finderId);
                  break;
                }
              }
            }

            return result;
          });

          logger.info(`[WeixinVideo] Extracted data from settings page:`, settingsData);

          if (settingsData.finderId) {
            finderId = settingsData.finderId;
            accountId = `weixin_video_${settingsData.finderId}`;
          }
        } catch (settingsError) {
          logger.warn('[WeixinVideo] Failed to fetch from settings page:', settingsError);
        }
      }

      logger.info(`[WeixinVideo] Final account info: id=${accountId}, name=${accountName}, avatar=${avatarUrl ? 'yes' : 'no'}, fans=${fansCount}`);

    } catch (error) {
      logger.warn('Failed to fetch WeixinVideo account info:', error);
    }

    return { accountId, accountName, avatarUrl, fansCount, worksCount };
  }

  /**
   * 获取小红书账号信息 - 通过 API 方式获取
   */
  private async fetchXiaohongshuAccountInfo(
    page: Page,
    _context: BrowserContext,
    cookies: CookieData[]
  ): Promise<AccountInfo> {
    let accountId = `xiaohongshu_${Date.now()}`;
    let accountName = '小红书账号';
    let avatarUrl = '';
    let fansCount = 0;
    let worksCount = 0;

    // 用于存储捕获的数据
    const capturedData: {
      userInfo?: {
        nickname?: string;
        avatar?: string;
        userId?: string;
        redId?: string;
        fans?: number;
        notes?: number;
      };
    } = {};

    try {
      // 从 Cookie 获取用户 ID
      const userIdCookie = cookies.find(c =>
        c.name === 'customer_id' || c.name === 'user_id' || c.name === 'web_session'
      );
      if (userIdCookie?.value) {
        accountId = `xiaohongshu_${userIdCookie.value.slice(0, 20)}`;
      }

      // 设置 API 响应监听器
      page.on('response', async (response) => {
        const url = response.url();
        try {
          // 监听用户信息 API
          if (url.includes('/api/galaxy/creator/home/personal_info') ||
            url.includes('/api/sns/web/v1/user/selfinfo') ||
            url.includes('/user/selfinfo')) {
            const data = await response.json();
            logger.info(`[Xiaohongshu API] User info response:`, JSON.stringify(data).slice(0, 500));

            // 解析用户信息
            const userInfo = data?.data?.user_info || data?.data || data;
            if (userInfo) {
              capturedData.userInfo = {
                nickname: userInfo.nickname || userInfo.name || userInfo.userName,
                avatar: userInfo.image || userInfo.avatar || userInfo.images,
                userId: userInfo.user_id || userInfo.userId,
                redId: userInfo.red_id || userInfo.redId,
                fans: userInfo.fans || userInfo.fansCount,
                notes: userInfo.notes || userInfo.noteCount,
              };
              logger.info(`[Xiaohongshu API] Captured user info:`, capturedData.userInfo);
            }
          }

          // 监听创作者主页数据
          if (url.includes('/api/galaxy/creator/home/home_page') ||
            url.includes('/api/galaxy/creator/data')) {
            const data = await response.json();
            logger.info(`[Xiaohongshu API] Creator home response:`, JSON.stringify(data).slice(0, 500));

            if (data?.data) {
              const homeData = data.data;
              // 获取粉丝数和笔记数
              if (homeData.fans_count !== undefined) {
                capturedData.userInfo = capturedData.userInfo || {};
                capturedData.userInfo.fans = homeData.fans_count;
              }
              if (homeData.note_count !== undefined) {
                capturedData.userInfo = capturedData.userInfo || {};
                capturedData.userInfo.notes = homeData.note_count;
              }
            }
          }
        } catch {
          // 忽略非 JSON 响应
        }
      });

      // 导航到小红书创作者中心
      logger.info('[Xiaohongshu] Navigating to creator center...');
      await page.goto('https://creator.xiaohongshu.com/creator/home', {
        waitUntil: 'domcontentloaded',
        timeout: 30000,
      });

      // 等待页面加载
      await page.waitForTimeout(3000);

      // 检查是否需要登录
      const currentUrl = page.url();
      if (currentUrl.includes('login') || currentUrl.includes('passport')) {
        logger.warn('[Xiaohongshu] Cookie expired, needs login');
        return this.getDefaultAccountInfo('xiaohongshu');
      }

      // 等待 API 响应
      await page.waitForTimeout(3000);

      // 如果 API 没有捕获到数据，尝试从页面提取
      if (!capturedData.userInfo?.nickname) {
        logger.info('[Xiaohongshu] API did not return data, extracting from page...');

        // 尝试获取用户名
        const nameSelectors = [
          '[class*="nickname"]',
          '[class*="user-name"]',
          '[class*="userName"]',
          '.user-info .name',
          '[class*="creator"] [class*="name"]',
        ];

        for (const selector of nameSelectors) {
          const el = await page.$(selector);
          if (el) {
            const text = await el.textContent();
            if (text?.trim() && text.trim().length < 50) {
              accountName = text.trim();
              logger.info(`[Xiaohongshu] Found name from page: ${accountName}`);
              break;
            }
          }
        }

        // 尝试获取头像
        const avatarSelectors = [
          '[class*="avatar"] img',
          '[class*="user-avatar"] img',
          '.user-info img',
          '[class*="creator"] img[src*="sns"]',
        ];

        for (const selector of avatarSelectors) {
          const el = await page.$(selector);
          if (el) {
            const src = await el.getAttribute('src');
            if (src && src.startsWith('http')) {
              avatarUrl = src;
              logger.info(`[Xiaohongshu] Found avatar from page: ${avatarUrl.slice(0, 50)}...`);
              break;
            }
          }
        }

        // 尝试获取粉丝数
        const statsText = await page.textContent('body');
        const fansMatch = statsText?.match(/粉丝[：:\s]*(\d+(?:\.\d+)?[万亿]?)/);
        if (fansMatch) {
          fansCount = this.parseChineseNumber(fansMatch[1]);
          logger.info(`[Xiaohongshu] Found fans count: ${fansCount}`);
        }

        const notesMatch = statsText?.match(/笔记[：:\s]*(\d+)/);
        if (notesMatch) {
          worksCount = parseInt(notesMatch[1], 10);
          logger.info(`[Xiaohongshu] Found notes count: ${worksCount}`);
        }
      }

      // 使用捕获的数据
      if (capturedData.userInfo) {
        if (capturedData.userInfo.nickname) {
          accountName = capturedData.userInfo.nickname;
        }
        if (capturedData.userInfo.avatar) {
          avatarUrl = capturedData.userInfo.avatar;
        }
        // 优先使用小红书号（redId）作为 accountId
        if (capturedData.userInfo.redId) {
          accountId = `xiaohongshu_${capturedData.userInfo.redId}`;
          logger.info(`[Xiaohongshu] Using redId as accountId: ${accountId}`);
        } else if (capturedData.userInfo.userId) {
          accountId = `xiaohongshu_${capturedData.userInfo.userId}`;
        }
        if (capturedData.userInfo.fans) {
          fansCount = capturedData.userInfo.fans;
        }
        if (capturedData.userInfo.notes) {
          worksCount = capturedData.userInfo.notes;
        }
      }

      // 如果还没获取到小红书号，尝试从页面文本中提取
      if (!accountId.match(/xiaohongshu_[a-zA-Z0-9_]+/) || accountId.includes('_' + Date.now().toString().slice(0, 8))) {
        const bodyText = await page.textContent('body');
        // 匹配小红书号格式：小红书号：xxxxxxx
        const xhsIdMatch = bodyText?.match(/小红书号[：:]\s*([a-zA-Z0-9_]+)/) ||
          bodyText?.match(/红书号[：:]\s*([a-zA-Z0-9_]+)/);
        if (xhsIdMatch) {
          accountId = `xiaohongshu_${xhsIdMatch[1]}`;
          logger.info(`[Xiaohongshu] Found 小红书号 from page text: ${accountId}`);
        }
      }

      logger.info(`[Xiaohongshu] Account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);

      // 获取作品列表 - 通过监听 API 接口
      const worksList: WorkItem[] = [];
      try {
        logger.info('[Xiaohongshu] Navigating to note manager page to fetch works...');

        // 存储所有捕获的笔记数据
        const allNotesData: Array<{
          noteId: string;
          title: string;
          coverUrl: string;
          status: number;
          publishTime: string;
          type: string;
          duration: number;
          likeCount: number;
          commentCount: number;
          collectCount: number;
          viewCount: number;
          shareCount: number;
        }> = [];

        let currentPage = 0;
        let hasMorePages = true;
        const maxPages = 20; // 最多获取20页，防止无限循环

        // 设置 API 响应监听器 - 在导航之前绑定
        let apiResponseReceived = false;
        let totalNotesCount = 0; // 从 tags 中获取的总作品数

        const notesApiHandler = async (response: import('playwright').Response) => {
          const url = response.url();
          try {
            // 监听小红书笔记列表 API
            // API: https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=X
            if (url.includes('/web_api/sns/v5/creator/note/user/posted') ||
              url.includes('/api/sns/v5/creator/note/user/posted') ||
              url.includes('creator/note/user/posted')) {
              const data = await response.json();
              logger.info(`[Xiaohongshu API] Notes list response: success=${data?.success}, code=${data?.code}, notes count=${data?.data?.notes?.length || 0}`);

              if ((data?.success || data?.code === 0) && data?.data) {
                apiResponseReceived = true;

                // 从 tags 中获取总作品数
                // tags 数组中 id="special.note_time_desc" 的项（"所有笔记"）包含总数
                if (data.data.tags && Array.isArray(data.data.tags)) {
                  const allNotesTag = data.data.tags.find((tag: { id?: string; notes_count?: number }) =>
                    tag.id === 'special.note_time_desc'
                  );
                  if (allNotesTag?.notes_count !== undefined) {
                    totalNotesCount = allNotesTag.notes_count;
                    logger.info(`[Xiaohongshu API] Total notes count from tags: ${totalNotesCount}`);
                  }
                }

                const notes = data.data.notes || [];
                for (const note of notes) {
                  // 根据 API 返回格式解析数据
                  // images_list 是数组，第一个元素包含 url
                  // 将 http:// 转换为 https:// 以确保图片能正常加载
                  let coverUrl = note.images_list?.[0]?.url || '';
                  if (coverUrl.startsWith('http://')) {
                    coverUrl = coverUrl.replace('http://', 'https://');
                  }
                  const duration = note.video_info?.duration || 0;

                  logger.info(`[Xiaohongshu API] Note: id=${note.id}, title="${note.display_title}", cover=${coverUrl ? coverUrl.slice(0, 60) + '...' : 'none'}`);

                  allNotesData.push({
                    noteId: note.id || '',
                    title: note.display_title || '',
                    coverUrl: coverUrl,
                    status: note.tab_status || 1, // 1=已发布
                    publishTime: note.time || '',
                    type: note.type || 'normal', // video/normal
                    duration: duration,
                    likeCount: note.likes || 0,
                    commentCount: note.comments_count || 0,
                    collectCount: note.collected_count || 0,
                    viewCount: note.view_count || 0,
                    shareCount: note.shared_count || 0,
                  });
                }

                // 检查是否还有更多页面
                // page=-1 表示没有更多数据
                if (data.data.page === -1 || notes.length === 0) {
                  hasMorePages = false;
                  logger.info(`[Xiaohongshu API] No more pages (page indicator: ${data.data.page})`);
                }
              } else {
                hasMorePages = false;
              }
            }
          } catch (e) {
            // 只在有相关 URL 时打印警告
            if (url.includes('creator/note')) {
              logger.warn('[Xiaohongshu API] Failed to parse notes response:', e);
            }
          }
        };

        // 先绑定监听器
        page.on('response', notesApiHandler);
        logger.info('[Xiaohongshu] API listener registered, navigating to note manager...');

        // 导航到笔记管理页面 - 使用 domcontentloaded 加快加载，避免 networkidle 超时
        try {
          await page.goto('https://creator.xiaohongshu.com/new/note-manager', {
            waitUntil: 'domcontentloaded',
            timeout: 30000,
          });
        } catch (navError) {
          // 导航超时不影响已捕获的 API 数据
          logger.warn('[Xiaohongshu] Navigation timeout, but API data may have been captured');
        }

        // 等待 API 响应
        await page.waitForTimeout(5000);
        logger.info(`[Xiaohongshu] After initial wait: apiResponseReceived=${apiResponseReceived}, notesCount=${allNotesData.length}`);

        // 如果监听器没有捕获到数据，尝试直接调用 API
        if (allNotesData.length === 0) {
          logger.info('[Xiaohongshu] No notes captured via listener, trying direct API call...');

          try {
            // 直接在页面上下文中调用 API
            const apiResponse = await page.evaluate(async () => {
              const response = await fetch('https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=0', {
                method: 'GET',
                credentials: 'include',
                headers: {
                  'Accept': 'application/json',
                },
              });
              return await response.json();
            });

            logger.info(`[Xiaohongshu] Direct API call result: success=${apiResponse?.success}, code=${apiResponse?.code}`);

            if ((apiResponse?.success || apiResponse?.code === 0) && apiResponse?.data) {
              // 从 tags 中获取总作品数
              if (apiResponse.data.tags && Array.isArray(apiResponse.data.tags)) {
                const allNotesTag = apiResponse.data.tags.find((tag: { id?: string; notes_count?: number }) =>
                  tag.id === 'special.note_time_desc'
                );
                if (allNotesTag?.notes_count !== undefined) {
                  totalNotesCount = allNotesTag.notes_count;
                  logger.info(`[Xiaohongshu API Direct] Total notes count from tags: ${totalNotesCount}`);
                }
              }

              const notes = apiResponse.data.notes || [];
              for (const note of notes) {
                // 将 http:// 转换为 https://
                let coverUrl = note.images_list?.[0]?.url || '';
                if (coverUrl.startsWith('http://')) {
                  coverUrl = coverUrl.replace('http://', 'https://');
                }
                const duration = note.video_info?.duration || 0;

                logger.info(`[Xiaohongshu API Direct] Note: id=${note.id}, cover=${coverUrl ? coverUrl.slice(0, 60) + '...' : 'none'}`);

                allNotesData.push({
                  noteId: note.id || '',
                  title: note.display_title || '',
                  coverUrl: coverUrl,
                  status: note.tab_status || 1,
                  publishTime: note.time || '',
                  type: note.type || 'normal',
                  duration: duration,
                  likeCount: note.likes || 0,
                  commentCount: note.comments_count || 0,
                  collectCount: note.collected_count || 0,
                  viewCount: note.view_count || 0,
                  shareCount: note.shared_count || 0,
                });
              }

              // 获取更多页面
              let pageNum = 1;
              let lastPage = apiResponse.data.page;
              while (lastPage !== -1 && pageNum < maxPages) {
                const nextResponse = await page.evaluate(async (p) => {
                  const response = await fetch(`https://edith.xiaohongshu.com/web_api/sns/v5/creator/note/user/posted?tab=0&page=${p}`, {
                    method: 'GET',
                    credentials: 'include',
                  });
                  return await response.json();
                }, pageNum);

                if (nextResponse?.data?.notes?.length > 0) {
                  for (const note of nextResponse.data.notes) {
                    // 将 http:// 转换为 https://
                    let coverUrl = note.images_list?.[0]?.url || '';
                    if (coverUrl.startsWith('http://')) {
                      coverUrl = coverUrl.replace('http://', 'https://');
                    }
                    const duration = note.video_info?.duration || 0;

                    allNotesData.push({
                      noteId: note.id || '',
                      title: note.display_title || '',
                      coverUrl: coverUrl,
                      status: note.tab_status || 1,
                      publishTime: note.time || '',
                      type: note.type || 'normal',
                      duration: duration,
                      likeCount: note.likes || 0,
                      commentCount: note.comments_count || 0,
                      collectCount: note.collected_count || 0,
                      viewCount: note.view_count || 0,
                      shareCount: note.shared_count || 0,
                    });
                  }
                  pageNum++;
                  lastPage = nextResponse.data.page;
                  if (lastPage === -1) break;
                } else {
                  break;
                }
              }
            }
          } catch (apiError) {
            logger.warn('[Xiaohongshu] Direct API call failed:', apiError);
          }
        }

        // 如果还是没有数据，尝试滚动加载
        if (allNotesData.length === 0) {
          logger.info('[Xiaohongshu] Still no notes, trying scroll to trigger API...');
          await page.waitForTimeout(2000);
        }

        // 滚动加载更多页面（如果通过监听器获取的数据）
        while (hasMorePages && currentPage < maxPages && allNotesData.length > 0 && apiResponseReceived) {
          currentPage++;
          const previousCount = allNotesData.length;

          // 滚动到页面底部触发加载更多
          await page.evaluate(() => {
            window.scrollTo(0, document.body.scrollHeight);
          });

          // 等待新数据加载
          await page.waitForTimeout(2000);

          // 如果没有新数据，退出循环
          if (allNotesData.length === previousCount) {
            logger.info(`[Xiaohongshu] No new notes loaded after scroll, stopping at page ${currentPage}`);
            break;
          }

          logger.info(`[Xiaohongshu] Page ${currentPage}: total ${allNotesData.length} notes`);
        }

        // 移除监听器
        page.off('response', notesApiHandler);

        logger.info(`[Xiaohongshu] Total notes captured: ${allNotesData.length}`);

        // 转换为 WorkItem 格式
        for (const note of allNotesData) {
          // 转换时长为 mm:ss 格式
          const minutes = Math.floor(note.duration / 60);
          const seconds = note.duration % 60;
          const durationStr = note.duration > 0
            ? `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
            : '';

          // 转换状态
          let statusStr = 'published';
          if (note.status === 0) statusStr = 'draft';
          else if (note.status === 2) statusStr = 'reviewing';
          else if (note.status === 3) statusStr = 'rejected';

          worksList.push({
            videoId: note.noteId,
            title: note.title || '无标题',
            coverUrl: note.coverUrl,
            duration: durationStr,
            publishTime: note.publishTime,
            status: statusStr,
            playCount: note.viewCount,
            likeCount: note.likeCount,
            commentCount: note.commentCount,
            shareCount: note.shareCount,
          });
        }

        logger.info(`[Xiaohongshu] Fetched ${worksList.length} works via API`);

        // 更新作品数：直接使用获取到的 notes 数量（更准确）
        // 只有当 notes 为空时才使用 tags 中的 notes_count
        if (worksList.length > 0) {
          worksCount = worksList.length;
          logger.info(`[Xiaohongshu] Using actual notes count: ${worksCount}`);
        } else if (totalNotesCount > 0) {
          worksCount = totalNotesCount;
          logger.info(`[Xiaohongshu] Using notes count from tags: ${worksCount}`);
        }
      } catch (worksError) {
        logger.warn('[Xiaohongshu] Failed to fetch works list:', worksError);
      }

      logger.info(`[Xiaohongshu] Final account info: id=${accountId}, name=${accountName}, fans=${fansCount}, works=${worksCount}`);
      return { accountId, accountName, avatarUrl, fansCount, worksCount, worksList };
    } catch (error) {
      logger.warn('[Xiaohongshu] Failed to fetch account info:', error);
    }

    return { accountId, accountName, avatarUrl, fansCount, worksCount };
  }

  /**
   * 解析中文数字（如 1.2万 -> 12000）
   */
  private parseChineseNumber(str: string): number {
    if (!str) return 0;

    let num = parseFloat(str);
    if (str.includes('万')) {
      num *= 10000;
    } else if (str.includes('亿')) {
      num *= 100000000;
    }
    return Math.floor(num);
  }

  /**
   * 获取平台配置
   */
  private getPlatformConfig(platform: PlatformType) {
    const configs: Record<string, { homeUrl: string; loginIndicators: string[] }> = {
      douyin: {
        homeUrl: 'https://creator.douyin.com/creator-micro/home',
        loginIndicators: ['login', 'passport', 'sso'],
      },
      bilibili: {
        homeUrl: 'https://member.bilibili.com/platform/home',
        loginIndicators: ['passport.bilibili.com', 'login'],
      },
      kuaishou: {
        homeUrl: 'https://cp.kuaishou.com/profile',
        loginIndicators: ['passport.kuaishou.com', 'login'],
      },
      xiaohongshu: {
        homeUrl: 'https://creator.xiaohongshu.com/',
        loginIndicators: ['login', 'passport'],
      },
      weixin_video: {
        homeUrl: 'https://channels.weixin.qq.com/platform',
        loginIndicators: ['login', 'passport'],
      },
      baijiahao: {
        homeUrl: 'https://baijiahao.baidu.com/builder/rc/home',
        loginIndicators: ['login', 'passport'],
      },
      toutiao: {
        homeUrl: 'https://mp.toutiao.com/profile_v4/index',
        loginIndicators: ['login', 'passport', 'sso'],
      },
      weibo: {
        homeUrl: 'https://weibo.com/u/',
        loginIndicators: ['login', 'passport'],
      },
      dayu: {
        homeUrl: 'https://mp.dayu.com/',
        loginIndicators: ['login', 'passport'],
      },
    };

    return configs[platform] || { homeUrl: '', loginIndicators: ['login'] };
  }

  /**
   * 百家号 - 直接通过 API 获取账号信息和作品列表
   */
  private async fetchBaijiahaoAccountInfoDirectApi(cookies: CookieData[]): Promise<AccountInfo> {
    logger.info(`[Baijiahao API] Fetching account info via direct API...`);

    // 构建 Cookie 字符串，确保格式正确
    const cookieString = cookies
      .map(c => `${c.name.trim()}=${c.value.trim()}`)
      .filter(c => c.includes('=')) // 过滤掉无效的 cookie
      .join('; ');

    logger.debug(`[Baijiahao API] Cookie string length: ${cookieString.length}, cookie count: ${cookies.length}`);

    const headers: Record<string, string> = {
      'Accept': '*/*',
      'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
      'Accept-Encoding': 'gzip, deflate, br',
      'Connection': 'keep-alive',
      'Cookie': cookieString,
      // 'Referer': 'https://baijiahao.baidu.com/builder/rc/home',
      // 'Origin': 'https://baijiahao.baidu.com',
      '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',
      // 'Sec-Fetch-Dest': 'empty',
      // 'Sec-Fetch-Mode': 'cors',
      // 'Sec-Fetch-Site': 'same-origin',
    };

    let accountInfo: AccountInfo = this.getDefaultAccountInfo('baijiahao');
    // 标记哪些字段已成功获取
    let fansCountFetched = false;
    let worksCountFetched = false;

    try {
      // 1. 获取账号基本信息 (appinfo API)
      logger.info(`[Baijiahao API] Step 1: Fetching appinfo...`);
      const appInfoResponse = await fetch('https://baijiahao.baidu.com/builder/app/appinfo', {
        method: 'GET',
        headers,
      });

      if (!appInfoResponse.ok) {
        logger.error(`[Baijiahao API] appinfo request failed: ${appInfoResponse.status}`);
        throw new Error(`appinfo request failed: ${appInfoResponse.status}`);
      }

      const appInfoData = await appInfoResponse.json() as {
        errno?: number;
        errmsg?: string;
        data?: {
          user?: {
            name?: string;
            avatar?: string;
            app_id?: string | number;
            userid?: number;
            status?: string;
          };
        };
      };

      logger.info(`[Baijiahao API] appinfo response: errno=${appInfoData.errno}, errmsg=${appInfoData.errmsg}`);

      if (appInfoData.errno !== 0) {
        logger.error(`[Baijiahao API] appinfo API error: errno=${appInfoData.errno}, errmsg=${appInfoData.errmsg}`);
        throw new Error(`appinfo API error: ${appInfoData.errmsg || 'Unknown error'}`);
      }

      if (!appInfoData.data?.user) {
        logger.error(`[Baijiahao API] No user data in appinfo response`);
        throw new Error('No user data in appinfo response');
      }

      const user = appInfoData.data.user;
      accountInfo.accountId = user.app_id ? `bjh_${user.app_id}` : accountInfo.accountId;
      accountInfo.accountName = user.name || accountInfo.accountName;
      // 处理头像 URL（可能是相对路径）
      if (user.avatar) {
        accountInfo.avatarUrl = user.avatar.startsWith('http')
          ? user.avatar
          : `https:${user.avatar}`;
      }
      logger.info(`[Baijiahao API] Got account info: name=${accountInfo.accountName}, id=${accountInfo.accountId}, avatar=${accountInfo.avatarUrl}`);

      // 2. 获取粉丝数 (growthInfo API)
      logger.info(`[Baijiahao API] Step 2: Fetching growth info...`);
      try {
        const growthInfoResponse = await fetch('https://baijiahao.baidu.com/cms-ui/rights/growth/get_info', {
          method: 'GET',
          headers,
        });

        if (growthInfoResponse.ok) {
          const growthData = await growthInfoResponse.json() as {
            errno?: number;
            errmsg?: string;
            data?: {
              total_fans?: number;
            };
          };

          logger.info(`[Baijiahao API] growth info response: errno=${growthData.errno}`);

          if (growthData.errno === 0 && growthData.data) {
            const fansCount = growthData.data.total_fans;
            if (fansCount !== undefined && fansCount !== null) {
              accountInfo.fansCount = fansCount;
              fansCountFetched = true;
              logger.info(`[Baijiahao API] Got fans count: ${accountInfo.fansCount}`);
            } else {
              logger.warn(`[Baijiahao API] growth info API returned no fans count`);
            }
          } else {
            logger.warn(`[Baijiahao API] growth info API error: errno=${growthData.errno}, errmsg=${growthData.errmsg}`);
          }
        } else {
          logger.warn(`[Baijiahao API] growth info request failed: ${growthInfoResponse.status}`);
        }
      } catch (growthError) {
        logger.warn(`[Baijiahao API] Failed to fetch growth info (non-critical):`, growthError);
        // 粉丝数获取失败不影响整体流程
      }

      // 3. 获取作品列表 (分页获取所有作品)
      logger.info(`[Baijiahao API] Step 3: Fetching works list...`);
      setTimeout(() => {
        console.log('1000ms');
      }, 1000);
      const worksList: WorkItem[] = [];
      let currentPage = 1;
      const pageSize = 20;
      let hasMore = true;
      let totalWorks = 0;
      let worksListError = false;

      while (hasMore && !worksListError) {
        try {
          const listUrl = `https://baijiahao.baidu.com/pcui/article/lists?currentPage=${currentPage}&pageSize=${pageSize}&search=&type=&collection=&startDate=&endDate=&clearBeforeFetch=false&dynamic=0`;

          logger.info(`[Baijiahao API] Fetching works page ${currentPage}...`);
          logger.debug(`[Baijiahao API] Request headers include Cookie: ${!!headers.Cookie}, Cookie length: ${headers.Cookie?.length || 0}`);

          const listResponse = await fetch(listUrl, {
            method: 'GET',
            headers,
          });

          if (!listResponse.ok) {
            const errorText = await listResponse.text();
            logger.warn(`[Baijiahao API] Failed to fetch works list page ${currentPage}: ${listResponse.status}`);
            logger.warn(`[Baijiahao API] Error response body: ${errorText}`);
            break;
          }

          const responseText = await listResponse.text();
          logger.info(`[Baijiahao API] ========== Works API Response (Page ${currentPage}) ==========`);
          logger.info(`[Baijiahao API] Full response: ${responseText}`);
          logger.info(`[Baijiahao API] ============================================================`);

          const listData = JSON.parse(responseText) as {
            errno?: number;
            errmsg?: string;
            data?: {
              list?: Array<{
                id?: string;
                article_id?: string;
                title?: string;
                cover_images?: string | string[];
                created_at?: string;
                create_time?: string;
                status?: string;
                read_amount?: number;
                read_count?: number;
                like_amount?: number;
                like_count?: number;
                comment_amount?: number;
                comment_count?: number;
                share_amount?: number;
                share_count?: number;
              }>;
              page?: {
                currentPage?: number;
                pageSize?: number;
                totalCount?: number;
                totalPage?: number;
              };
              total?: number; // 兼容旧格式
            };
          };

          // 处理分散认证问题 (errno=10001402)，重试一次
          if (listData.errno === 10001402) {
            logger.warn(`[Baijiahao API] Dispersed authentication issue (errno=10001402) on page ${currentPage}, retrying after 3 seconds...`);
            logger.debug(`[Baijiahao API] Request URL: ${listUrl}`);
            logger.debug(`[Baijiahao API] Cookie header present: ${!!headers.Cookie}, length: ${headers.Cookie?.length || 0}`);

            await new Promise(resolve => setTimeout(resolve, 3000));

            // 重试一次，确保 headers 包含 Cookie
            const retryResponse = await fetch(listUrl, {
              method: 'GET',
              headers: {
                ...headers,
                'Cookie': cookieString, // 确保 Cookie 被正确传递
              },
            });

            if (retryResponse.ok) {
              const retryResponseText = await retryResponse.text();
              logger.info(`[Baijiahao API] ========== Works API Retry Response (Page ${currentPage}) ==========`);
              logger.info(`[Baijiahao API] Full retry response: ${retryResponseText}`);
              logger.info(`[Baijiahao API] ============================================================`);

              const retryData = JSON.parse(retryResponseText) as typeof listData;
              if (retryData.errno === 0) {
                logger.info(`[Baijiahao API] Retry successful for page ${currentPage}`);
                Object.assign(listData, retryData);
              } else if (retryData.errno === 10001402) {
                logger.error(`[Baijiahao API] Retry still failed with errno=10001402, cookie may be invalid or expired`);
                logger.error(`[Baijiahao API] Retry response data: ${JSON.stringify(retryData, null, 2)}`);
                // 如果重试仍然失败，可能是 Cookie 问题，记录详细信息
                logger.error(`[Baijiahao API] Cookie info: ${cookieString.substring(0, 200)}...`);
                // 标记错误，但不完全失败，继续返回已获取的账号信息
                worksListError = true;
                logger.warn(`[Baijiahao API] Works list fetch failed, but will return other account info (name, fans count)`);
                break;
              } else {
                logger.warn(`[Baijiahao API] Retry still failed: errno=${retryData.errno}, errmsg=${retryData.errmsg}`);
                break;
              }
            } else {
              logger.warn(`[Baijiahao API] Retry request failed: ${retryResponse.status}`);
              break;
            }
          }

          if (listData.errno !== 0) {
            logger.warn(`[Baijiahao API] API returned error on page ${currentPage}: errno=${listData.errno}, errmsg=${listData.errmsg}`);
            logger.warn(`[Baijiahao API] Error response data: ${JSON.stringify(listData, null, 2)}`);
            // 如果不是 10001402 错误，标记为错误但继续返回其他信息
            if (listData.errno !== 10001402) {
              worksListError = true;
              logger.warn(`[Baijiahao API] Works list fetch failed with errno=${listData.errno}, but will return other account info`);
            }
            break;
          }

          const list = listData.data?.list || [];
          // 优先使用 data.page.totalCount，如果没有则使用 data.total（兼容旧格式）
          totalWorks = listData.data?.page?.totalCount || listData.data?.total || 0;
          logger.info(`[Baijiahao API] Got ${list.length} works on page ${currentPage}, total: ${totalWorks}`);

          for (const item of list) {
            // 处理 cover_images 可能是字符串（JSON）或数组
            let coverUrl = '';
            if (item.cover_images) {
              if (Array.isArray(item.cover_images)) {
                coverUrl = item.cover_images[0] || '';
              } else if (typeof item.cover_images === 'string') {
                try {
                  const coverArray = JSON.parse(item.cover_images);
                  if (Array.isArray(coverArray) && coverArray.length > 0) {
                    coverUrl = typeof coverArray[0] === 'string' ? coverArray[0] : coverArray[0]?.src || coverArray[0]?.ori_src || '';
                  }
                } catch {
                  coverUrl = item.cover_images;
                }
              }
            }

            worksList.push({
              videoId: item.id || item.article_id || `bjh_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
              title: item.title || '',
              coverUrl: coverUrl,
              duration: '00:00',
              publishTime: item.created_at || item.create_time || new Date().toISOString(),
              status: item.status || 'published',
              playCount: item.read_amount || item.read_count || 0,
              likeCount: item.like_amount || item.like_count || 0,
              commentCount: item.comment_amount || item.comment_count || 0,
              shareCount: item.share_amount || item.share_count || 0,
            });
          }

          // 检查是否还有更多
          if (list.length < pageSize) {
            hasMore = false;
            logger.info(`[Baijiahao API] No more works, stopping at page ${currentPage}`);
          } else {
            currentPage++;
            // 防止无限循环，最多获取 10 页（200 个作品）
            if (currentPage > 10) {
              logger.warn(`[Baijiahao API] Reached max pages (10), stopping. Total fetched: ${worksList.length}, API total: ${totalWorks}`);
              hasMore = false;
            }
          }
        } catch (pageError) {
          logger.error(`[Baijiahao API] Error fetching page ${currentPage}:`, pageError);
          break;
        }
      }

      accountInfo.worksList = worksList;
      // 使用 API 返回的 total 字段作为作品总数，而不是已获取的作品列表长度
      // 因为可能只获取了部分作品（最多 10 页），但 total 是真实的总数
      if (totalWorks > 0) {
        accountInfo.worksCount = totalWorks;
        worksCountFetched = true;
      } else if (worksList.length > 0) {
        // 如果 API 没有返回 total，但获取到了作品列表，使用列表长度
        accountInfo.worksCount = worksList.length;
        worksCountFetched = true;
      }

      if (worksListError) {
        logger.warn(`[Baijiahao API] Works list fetch encountered errors, but returning partial account info`);
        logger.info(`[Baijiahao API] Account info (partial): name=${accountInfo.accountName}, fans=${accountInfo.fansCount} (fetched: ${fansCountFetched}), works=${accountInfo.worksCount} (fetched: ${worksCountFetched})`);
      } else {
        logger.info(`[Baijiahao API] Successfully fetched account info: name=${accountInfo.accountName}, fans=${accountInfo.fansCount} (fetched: ${fansCountFetched}), works=${accountInfo.worksCount} (fetched: ${worksCountFetched}, API total: ${totalWorks}, fetched list: ${worksList.length})`);
      }

      return accountInfo;
    } catch (error) {
      logger.error(`[Baijiahao API] Failed to fetch account info:`, error);
      // 返回默认信息，但保留已获取的部分数据
      return accountInfo;
    }
  }

  /**
   * 通过 Python API 获取账号信息
   */
  private async fetchAccountInfoViaPython(platform: PlatformType, cookies: CookieData[]): Promise<AccountInfo> {
    logger.info(`[Python API] Fetching account info for ${platform}...`);

    try {
      // 检查 Python 服务是否可用
      const pythonAvailable = await this.checkPythonServiceAvailable();
      if (!pythonAvailable) {
        logger.warn(`[Python API] Service not available, returning default info`);
        return this.getDefaultAccountInfo(platform);
      }

      // 构建 Cookie 字符串
      const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');

      // 调用 Python API
      const response = await fetch(`${PYTHON_SERVICE_URL}/account_info`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          platform,
          cookie: cookieString,
        }),
      });

      if (!response.ok) {
        logger.warn(`[Python API] account_info returned ${response.status}`);
        return this.getDefaultAccountInfo(platform);
      }

      const result = await response.json() as {
        success: boolean;
        account_id?: string;
        account_name?: string;
        avatar_url?: string;
        fans_count?: number;
        works_count?: number;
        error?: string;
        need_login?: boolean;
      };

      logger.info(`[Python API] account_info result: success=${result.success}, name=${result.account_name}`);

      if (result.success && result.account_name) {
        return {
          accountId: result.account_id || `${platform}_${Date.now()}`,
          accountName: result.account_name,
          avatarUrl: result.avatar_url || '',
          fansCount: result.fans_count || 0,
          worksCount: result.works_count || 0,
        };
      }

      if (result.need_login) {
        logger.warn(`[Python API] Account needs re-login`);
      }

      logger.warn(`[Python API] Failed to get account info: ${result.error}`);
      return this.getDefaultAccountInfo(platform);
    } catch (error) {
      logger.error(`[Python API] Failed to fetch account info for ${platform}:`, error);
      return this.getDefaultAccountInfo(platform);
    }
  }

  /**
   * 获取默认账号信息
   */
  private getDefaultAccountInfo(platform: PlatformType): AccountInfo {
    // 平台友好名称映射
    const platformNames: Record<string, string> = {
      douyin: '抖音',
      xiaohongshu: '小红书',
      kuaishou: '快手',
      weixin_video: '视频号',
      bilibili: 'B站',
      toutiao: '头条',
      baijiahao: '百家号',
    };
    const name = platformNames[platform] || platform;
    return {
      accountId: `${platform}_${Date.now()}`,
      accountName: `${name}账号`,
      avatarUrl: '',
      fansCount: 0,
      worksCount: 0,
    };
  }

  /**
   * 获取抖音评论 - 逐个选择作品获取评论
   */
  async fetchDouyinComments(cookies: CookieData[]): Promise<WorkComments[]> {
    const browser = await chromium.launch({
      headless: true,
      args: ['--no-sandbox', '--disable-setuid-sandbox'],
    });

    const allWorkComments: WorkComments[] = [];

    try {
      const context = await browser.newContext({
        viewport: { width: 1920, height: 1080 },
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      });

      // 设置 Cookie
      const playwrightCookies = cookies.map(c => ({
        name: c.name,
        value: c.value,
        domain: c.domain || '.douyin.com',
        path: c.path || '/',
      }));
      await context.addCookies(playwrightCookies);

      const page = await context.newPage();

      // 导航到评论管理页面
      logger.info('Navigating to Douyin comment management page...');
      await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
        waitUntil: 'domcontentloaded',
        timeout: 30000,
      });

      await page.waitForTimeout(3000);

      // 点击"选择作品"按钮
      logger.info('Looking for "选择作品" button...');
      const selectWorkBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品"), div:has-text("选择作品")');

      if (selectWorkBtn) {
        await selectWorkBtn.click();
        await page.waitForTimeout(2000);
        logger.info('Clicked "选择作品" button');
      } else {
        // 如果没有选择作品按钮，可能已经有作品被选中，直接获取当前评论
        logger.info('No "选择作品" button found, fetching current comments...');
        const currentComments = await this.extractCommentsFromPage(page);
        if (currentComments.length > 0) {
          allWorkComments.push({
            videoId: 'current',
            videoTitle: '当前作品',
            videoCoverUrl: '',
            comments: currentComments,
          });
        }
        await page.close();
        await context.close();
        await browser.close();
        return allWorkComments;
      }

      // 获取作品列表
      const worksList = await page.evaluate(() => {
        const works: Array<{ videoId: string; title: string; coverUrl: string }> = [];

        // 查找作品列表容器（弹窗中的作品选择列表）
        const workItems = document.querySelectorAll('[class*="video-card"], [class*="work-item"], [class*="content-item"]');

        workItems.forEach((item, index) => {
          const titleEl = item.querySelector('[class*="title"], [class*="desc"]');
          const coverEl = item.querySelector('img, [class*="cover"]');

          const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;
          let coverUrl = '';

          if (coverEl) {
            coverUrl = (coverEl as HTMLImageElement).src ||
              coverEl.getAttribute('style')?.match(/url\(['"]?([^'")\s]+)['"]?\)/)?.[1] || '';
          }

          // 获取 video ID（从数据属性或其他方式）
          const videoId = item.getAttribute('data-video-id') ||
            item.getAttribute('data-id') ||
            `video_${index}`;

          works.push({ videoId, title, coverUrl });
        });

        return works;
      });

      logger.info(`Found ${worksList.length} works in the selector`);

      // 如果有作品列表，逐个选择并获取评论
      if (worksList.length > 0) {
        for (let i = 0; i < worksList.length; i++) {
          try {
            logger.info(`Processing work ${i + 1}/${worksList.length}: ${worksList[i].title}`);

            // 点击选择该作品
            const workItem = await page.$(`[class*="video-card"]:nth-child(${i + 1}), [class*="work-item"]:nth-child(${i + 1})`);
            if (workItem) {
              await workItem.click();
              await page.waitForTimeout(2000);

              // 点击确认按钮（如果有）
              const confirmBtn = await page.$('button:has-text("确定"), button:has-text("确认")');
              if (confirmBtn) {
                await confirmBtn.click();
                await page.waitForTimeout(2000);
              }
            }

            // 等待评论加载
            await page.waitForTimeout(2000);

            // 提取评论
            const comments = await this.extractCommentsFromPage(page);

            if (comments.length > 0) {
              allWorkComments.push({
                videoId: worksList[i].videoId,
                videoTitle: worksList[i].title,
                videoCoverUrl: worksList[i].coverUrl,
                comments,
              });
              logger.info(`Extracted ${comments.length} comments for work: ${worksList[i].title}`);
            }

            // 重新打开选择作品弹窗（如果需要继续选择其他作品）
            if (i < worksList.length - 1) {
              const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择作品")');
              if (selectBtn) {
                await selectBtn.click();
                await page.waitForTimeout(2000);
              }
            }
          } catch (workError) {
            logger.warn(`Failed to process work ${i + 1}:`, workError);
          }
        }
      } else {
        // 没有找到作品列表，尝试直接从页面获取评论
        const comments = await this.extractCommentsFromPage(page);
        if (comments.length > 0) {
          // 获取当前显示的作品信息
          const currentWork = await page.evaluate(() => {
            const titleEl = document.querySelector('[class*="video-title"], [class*="content-title"]');
            const coverEl = document.querySelector('[class*="video-cover"] img, [class*="cover"] img');

            return {
              title: titleEl?.textContent?.trim() || '当前作品',
              coverUrl: (coverEl as HTMLImageElement)?.src || '',
            };
          });

          allWorkComments.push({
            videoId: 'current',
            videoTitle: currentWork.title,
            videoCoverUrl: currentWork.coverUrl,
            comments,
          });
        }
      }

      await page.close();
      await context.close();
      await browser.close();

      logger.info(`Total: fetched comments from ${allWorkComments.length} works`);
      return allWorkComments;

    } catch (error) {
      logger.error('Error fetching Douyin comments:', error);
      await browser.close();
      return allWorkComments;
    }
  }

  /**
   * 从页面提取评论列表
   * 使用抖音创作者中心的精确选择器
   * 根据实际 HTML 结构：
   * - 评论容器: container-sXKyMs (或类似 container-xxx)
   * - 用户名: username-aLgaNB (或类似 username-xxx)
   * - 时间: time-NRtTXO (或类似 time-xxx)
   * - 评论内容: comment-content-text-JvmAKq (或类似 comment-content-text-xxx)
   * - 头像: avatar-BRKDsF (或类似 avatar-xxx)
   */
  private async extractCommentsFromPage(page: Page): Promise<CommentItem[]> {
    return page.evaluate(() => {
      const comments: Array<{
        commentId: string;
        authorId: string;
        authorName: string;
        authorAvatar: string;
        content: string;
        likeCount: number;
        commentTime: string;
      }> = [];

      const seenContents = new Set<string>();

      // 方法1: 直接查找所有评论容器 (container-xxx 类名)
      // 评论容器通常包含 checkbox、avatar、content 等子元素
      const allContainers = document.querySelectorAll('[class*="container-"]');
      const commentContainers: Element[] = [];

      allContainers.forEach(container => {
        // 检查是否是评论容器：包含用户名和评论内容
        const hasUsername = container.querySelector('[class*="username-"]');
        const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
        if (hasUsername && hasCommentContent) {
          commentContainers.push(container);
        }
      });

      console.log(`Found ${commentContainers.length} comment containers`);

      // 如果方法1没找到，尝试方法2：通过评论内容元素向上查找
      if (commentContainers.length === 0) {
        const contentElements = document.querySelectorAll('[class*="comment-content-text-"]');
        console.log(`Found ${contentElements.length} content elements, searching parents...`);

        contentElements.forEach(contentEl => {
          let parent = contentEl.parentElement;
          // 向上查找最多 10 层
          for (let i = 0; i < 10 && parent; i++) {
            const className = parent.className || '';
            // 查找包含 container- 的父元素
            if (className.includes('container-')) {
              if (!commentContainers.includes(parent)) {
                commentContainers.push(parent);
              }
              break;
            }
            parent = parent.parentElement;
          }
        });
      }

      console.log(`Total comment containers: ${commentContainers.length}`);

      commentContainers.forEach((container, index) => {
        try {
          // 提取用户名 - 使用 username-xxx 选择器
          let authorName = '';
          const usernameEl = container.querySelector('[class*="username-"]');
          if (usernameEl && usernameEl.textContent) {
            authorName = usernameEl.textContent.trim();
          }
          if (!authorName) authorName = '未知用户';

          // 提取头像 - 从 avatar-xxx 容器内的 img 提取
          let authorAvatar = '';
          const avatarContainer = container.querySelector('[class*="avatar-"]');
          if (avatarContainer) {
            const avatarImg = avatarContainer.querySelector('img');
            if (avatarImg) {
              authorAvatar = avatarImg.src || '';
            }
          }

          // 提取时间 - 使用 time-xxx 选择器
          let commentTime = '';
          const timeEl = container.querySelector('[class*="time-"]');
          if (timeEl && timeEl.textContent) {
            commentTime = timeEl.textContent.trim();
          }

          // 提取评论内容 - 使用 comment-content-text-xxx 选择器
          let content = '';
          const contentEl = container.querySelector('[class*="comment-content-text-"]');
          if (contentEl && contentEl.textContent) {
            content = contentEl.textContent.trim();
          }

          // 跳过空内容
          if (!content || content.length < 1) {
            console.log(`[${index}] Skipping empty content`);
            return;
          }

          // 去重 (基于用户名+内容)
          const contentKey = `${authorName}||${content}`;
          if (seenContents.has(contentKey)) {
            console.log(`[${index}] Skipping duplicate: ${authorName} - ${content.slice(0, 20)}`);
            return;
          }
          seenContents.add(contentKey);

          // 提取点赞数 - 从 operations-xxx 或 item-xxx 中提取
          let likeCount = 0;
          const operationsEl = container.querySelector('[class*="operations-"]');
          if (operationsEl) {
            // 查找第一个 item-xxx，通常是点赞数
            const firstItem = operationsEl.querySelector('[class*="item-"]');
            if (firstItem) {
              const text = firstItem.textContent || '';
              const match = text.match(/(\d+)/);
              if (match) {
                likeCount = parseInt(match[1], 10);
              }
            }
          }

          // 生成唯一 ID
          const contentHash = content.slice(0, 30) + authorName + commentTime;
          const commentId = `dy_${btoa(encodeURIComponent(contentHash)).slice(0, 20)}`;

          comments.push({
            commentId,
            authorId: authorName,
            authorName,
            authorAvatar,
            content,
            likeCount,
            commentTime,
          });

          console.log(`[${index}] Extracted: ${authorName} - ${content.slice(0, 30)} (${commentTime})`);
        } catch (err) {
          console.error(`[${index}] Error extracting comment:`, err);
        }
      });

      console.log(`Successfully extracted ${comments.length} comments`);
      return comments;
    });
  }

  /**
   * 获取抖音评论 - 通过监听 API 请求 (推荐方式)
   * 使用无头浏览器，通过拦截网络请求直接获取 API 数据
   * 更稳定、更高效
   */
  async fetchDouyinCommentsByApiInterception(cookies: CookieData[]): Promise<WorkComments[]> {
    const browser = await chromium.launch({
      headless: true, // 无头模式
      args: ['--no-sandbox', '--disable-setuid-sandbox'],
    });

    const allWorkComments: WorkComments[] = [];
    // 存储捕获的 API 数据
    const capturedWorks: Array<{
      awemeId: string;
      title: string;
      coverUrl: string;
      commentCount: number;
    }> = [];
    const capturedComments: Map<string, CommentItem[]> = new Map();

    try {
      const context = await browser.newContext({
        viewport: { width: 1920, height: 1080 },
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      });

      // 设置 Cookie
      const playwrightCookies = cookies.map(c => ({
        name: c.name,
        value: c.value,
        domain: c.domain || '.douyin.com',
        path: c.path || '/',
      }));
      await context.addCookies(playwrightCookies);
      logger.info(`[API Interception] Set ${playwrightCookies.length} cookies`);

      const page = await context.newPage();

      // 监听网络响应
      page.on('response', async (response) => {
        const url = response.url();

        try {
          // 监听作品列表 API - 支持新旧两种接口
          // 新接口: /janus/douyin/creator/pc/work_list (aweme_list 字段)
          // 旧接口: /creator/item/list (item_info_list 字段)
          if (url.includes('/work_list') || url.includes('/creator/item/list')) {
            const data = await response.json();

            // 新接口: aweme_list
            if (data?.aweme_list && data.aweme_list.length > 0) {
              for (const aweme of data.aweme_list) {
                const awemeId = String(aweme.aweme_id || '');
                if (!awemeId) continue;

                const statistics = aweme.statistics || {};
                const commentCount = parseInt(String(statistics.comment_count || '0'), 10);

                let title = aweme.item_title || '';
                if (!title) {
                  const desc = aweme.desc || aweme.caption || '';
                  title = desc.split('\n')[0].slice(0, 50) || '无标题';
                }

                let coverUrl = '';
                if (aweme.Cover?.url_list?.length > 0) {
                  coverUrl = aweme.Cover.url_list[0];
                } else if (aweme.video?.cover?.url_list?.length > 0) {
                  coverUrl = aweme.video.cover.url_list[0];
                }

                capturedWorks.push({
                  awemeId,
                  title,
                  coverUrl,
                  commentCount,
                });
              }
              logger.info(`[API] Captured ${data.aweme_list.length} works from work_list API`);
            }

            // 旧接口: item_info_list
            const itemList = data?.item_info_list || data?.item_list || [];
            if (itemList.length > 0) {
              for (const item of itemList) {
                capturedWorks.push({
                  awemeId: item.item_id_plain || item.aweme_id || '',
                  title: item.title || '无标题',
                  coverUrl: item.cover_image_url || '',
                  commentCount: item.comment_count || 0,
                });
              }
              logger.info(`[API] Captured ${itemList.length} works from item/list API`);
            }
          }

          // 监听评论列表 API（两种格式）
          // 格式1: /comment/list/select/ - 初始加载，返回 { comments: [...] }
          // 格式2: /creator/comment/list/ - 切换作品后，返回 { comment_info_list: [...] }
          if (url.includes('/comment/list') || url.includes('/comment/read')) {
            const data = await response.json();
            // 从 URL 中提取 aweme_id
            const awemeIdMatch = url.match(/aweme_id=(\d+)/);
            const awemeId = awemeIdMatch?.[1] || '';

            let comments: CommentItem[] = [];

            // 格式1: 初始加载的评论 API (comment/list/select)
            if (data?.comments && Array.isArray(data.comments) && data.comments.length > 0) {
              comments = data.comments.map((c: Record<string, unknown>) => {
                const user = c.user as Record<string, unknown> | undefined;
                const avatarThumb = user?.avatar_thumb as Record<string, unknown> | undefined;
                const avatarUrls = avatarThumb?.url_list as string[] | undefined;

                return {
                  commentId: String(c.cid || ''),
                  authorId: String(user?.uid || ''),
                  authorName: String(user?.nickname || '匿名'),
                  authorAvatar: avatarUrls?.[0] || '',
                  content: String(c.text || ''),
                  likeCount: Number(c.digg_count || 0),
                  commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
                  videoId: String(c.aweme_id || awemeId),
                };
              });
              logger.info(`[API] Format1 (comments): Captured ${comments.length} comments`);
            }

            // 格式2: 切换作品后的评论 API (creator/comment/list)
            if (data?.comment_info_list && Array.isArray(data.comment_info_list) && data.comment_info_list.length > 0) {
              comments = data.comment_info_list.map((c: Record<string, unknown>) => {
                const userInfo = c.user_info as Record<string, unknown> | undefined;

                return {
                  commentId: String(c.comment_id || ''),
                  authorId: String(userInfo?.user_id || ''),
                  authorName: String(userInfo?.screen_name || '匿名'),
                  authorAvatar: String(userInfo?.avatar_url || ''),
                  content: String(c.text || ''),
                  likeCount: Number(c.digg_count || 0),
                  commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
                  videoId: awemeId, // 这种格式没有直接返回 aweme_id
                };
              });
              logger.info(`[API] Format2 (comment_info_list): Captured ${comments.length} comments`);
            }

            if (comments.length > 0) {
              const videoId = comments[0]?.videoId || awemeId;
              if (videoId) {
                const existing = capturedComments.get(videoId) || [];
                capturedComments.set(videoId, [...existing, ...comments]);
                logger.info(`[API] Total captured ${comments.length} comments for aweme ${videoId}`);
              }
            }
          }
        } catch {
          // 忽略非 JSON 响应
        }
      });

      // 导航到创作者中心页面（设置好 Cookie 后）
      logger.info('[API Interception] Navigating to creator page...');
      await page.goto('https://creator.douyin.com/creator-micro/home', {
        waitUntil: 'domcontentloaded',
        timeout: 60000,
      });

      // 等待页面加载
      await page.waitForTimeout(3000);

      // 检查是否需要登录
      const currentUrl = page.url();
      if (currentUrl.includes('login') || currentUrl.includes('passport')) {
        logger.warn('[API Interception] Cookie expired');
        return [];
      }

      // 方式1：直接调用 API 获取作品列表（优先）
      logger.info('[API Interception] Fetching works via direct API...');
      let works = await this.fetchWorksDirectApi(page);

      // 方式2：如果直接调用失败，尝试通过页面触发 API
      if (works.length === 0) {
        logger.info('[API Interception] Direct API failed, trying page navigation...');
        await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
          waitUntil: 'networkidle',
          timeout: 60000,
        });
        await page.waitForTimeout(3000);

        // 点击"选择作品"按钮触发作品列表 API
        const selectBtn = await page.$('button:has-text("选择作品"), [class*="select"]:has-text("选择")');
        if (selectBtn) {
          await selectBtn.click();
          await page.waitForTimeout(3000);
        }

        // 使用监听到的数据
        works = capturedWorks;
      }

      logger.info(`[API Interception] Total works: ${works.length}`);

      // 获取有评论的作品
      const worksWithComments = works.filter(w => w.commentCount > 0);
      logger.info(`[API Interception] Works with comments: ${worksWithComments.length}`);

      // 如果有评论的作品，需要导航到评论管理页面并逐个切换获取
      if (worksWithComments.length > 0) {
        // 先尝试直接调用 API 获取评论
        for (const work of worksWithComments) {
          logger.info(`[API Interception] Trying direct API for: ${work.title.slice(0, 30)}... (${work.commentCount} comments)`);

          let comments = capturedComments.get(work.awemeId) || [];

          if (comments.length === 0) {
            comments = await this.fetchCommentsDirectApi(page, work.awemeId);
          }

          if (comments.length > 0) {
            allWorkComments.push({
              videoId: work.awemeId,
              videoTitle: work.title,
              videoCoverUrl: work.coverUrl,
              comments,
            });
            logger.info(`[API Interception] Got ${comments.length} comments for ${work.awemeId} via direct API`);
          }
        }

        // 如果直接 API 没有获取到足够的评论，使用页面交互方式
        const worksNeedingPageMethod = worksWithComments.filter(w => {
          const found = allWorkComments.find(wc => wc.videoId === w.awemeId);
          return !found || found.comments.length === 0;
        });

        if (worksNeedingPageMethod.length > 0) {
          logger.info(`[API Interception] ${worksNeedingPageMethod.length} works need page interaction method`);

          // works 是所有作品的列表（包括没有评论的），弹窗中的顺序应该和这个一致
          // worksWithComments 是有评论的作品列表
          logger.info(`[Page Method] All works: ${works.length}, works with comments: ${worksWithComments.length}`);
          logger.info(`[Page Method] Works with comments IDs: ${worksWithComments.map(w => w.awemeId).join(', ')}`);

          // 构建作品索引映射：在所有作品列表中，每个有评论的作品的索引是多少
          const workIndexMap = new Map<string, number>();
          works.forEach((w, idx) => {
            if (w.commentCount > 0) {
              workIndexMap.set(w.awemeId, idx);
            }
          });
          logger.info(`[Page Method] Work index map: ${JSON.stringify(Object.fromEntries(workIndexMap))}`);

          // 导航到评论管理页面
          logger.info('[Page Method] Navigating to comment management page...');
          await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
            waitUntil: 'domcontentloaded',
            timeout: 60000,
          });

          // 等待页面加载
          await page.waitForTimeout(5000);

          // 用于存储最新捕获的评论和 aweme_id
          const latestHolder: { comments: CommentItem[]; awemeId: string } = { comments: [], awemeId: '' };

          // 设置监听器 - 捕获评论 API 响应
          page.on('response', async (response) => {
            const url = response.url();
            if (url.includes('/comment/list') || url.includes('/comment/read')) {
              try {
                const jsonData = await response.json();
                let parsedComments: CommentItem[] = [];
                let capturedAwemeId = '';

                // 从 URL 中提取 aweme_id（格式1有）
                const awemeIdMatch = url.match(/aweme_id=(\d+)/);
                capturedAwemeId = awemeIdMatch?.[1] || '';

                // 格式1: { comments: [...] }
                if (jsonData?.comments && Array.isArray(jsonData.comments) && jsonData.comments.length > 0) {
                  // 从评论中提取 aweme_id
                  const firstComment = jsonData.comments[0] as Record<string, unknown>;
                  if (!capturedAwemeId && firstComment.aweme_id) {
                    capturedAwemeId = String(firstComment.aweme_id);
                  }

                  parsedComments = jsonData.comments.map((c: Record<string, unknown>) => ({
                    commentId: String((c as { cid?: string }).cid || ''),
                    authorId: String(((c as { user?: { uid?: string } }).user)?.uid || ''),
                    authorName: String(((c as { user?: { nickname?: string } }).user)?.nickname || '匿名'),
                    authorAvatar: ((c as { user?: { avatar_thumb?: { url_list?: string[] } } }).user)?.avatar_thumb?.url_list?.[0] || '',
                    content: String((c as { text?: string }).text || ''),
                    likeCount: Number((c as { digg_count?: number }).digg_count || 0),
                    commentTime: new Date(Number((c as { create_time?: number }).create_time || 0) * 1000).toISOString(),
                    videoId: capturedAwemeId,
                  }));
                  logger.info(`[Comment API] Format1: ${parsedComments.length} comments, aweme_id: ${capturedAwemeId}`);
                }

                // 格式2: { comment_info_list: [...] }
                if (jsonData?.comment_info_list && Array.isArray(jsonData.comment_info_list) && jsonData.comment_info_list.length > 0) {
                  parsedComments = jsonData.comment_info_list.map((c: Record<string, unknown>) => {
                    const userInfo = c.user_info as Record<string, unknown> | undefined;
                    return {
                      commentId: String(c.comment_id || ''),
                      authorId: String(userInfo?.user_id || ''),
                      authorName: String(userInfo?.screen_name || '匿名'),
                      authorAvatar: String(userInfo?.avatar_url || ''),
                      content: String(c.text || ''),
                      likeCount: Number(c.digg_count || 0),
                      commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
                      videoId: '', // 格式2没有aweme_id，稍后填充
                    };
                  });
                  logger.info(`[Comment API] Format2: ${parsedComments.length} comments (no aweme_id)`);
                }

                if (parsedComments.length > 0) {
                  latestHolder.comments = parsedComments;
                  latestHolder.awemeId = capturedAwemeId;
                }
              } catch {
                // 忽略
              }
            }
          });

          // 等待第一个作品的评论加载（格式1，有 aweme_id）
          await page.waitForTimeout(4000);

          // 处理第一个作品（页面加载时自动显示，格式1有aweme_id可以直接匹配）
          if (latestHolder.comments.length > 0 && latestHolder.awemeId) {
            const matchedWork = works.find(w => w.awemeId === latestHolder.awemeId);
            if (matchedWork) {
              allWorkComments.push({
                videoId: matchedWork.awemeId,
                videoTitle: matchedWork.title,
                videoCoverUrl: matchedWork.coverUrl,
                comments: latestHolder.comments,
              });
              logger.info(`[Page Method] First work (by aweme_id): ${latestHolder.comments.length} comments for ${matchedWork.awemeId}`);
            }
          }

          // 遍历其他有评论的作品
          for (const work of worksWithComments) {
            // 检查是否已获取
            const existing = allWorkComments.find(wc => wc.videoId === work.awemeId);
            if (existing) {
              logger.info(`[Page Method] Skip ${work.awemeId}, already got ${existing.comments.length} comments`);
              continue;
            }

            // 获取该作品在所有作品列表中的索引
            const workIndex = workIndexMap.get(work.awemeId);
            if (workIndex === undefined) {
              logger.warn(`[Page Method] Work ${work.awemeId} not found in index map`);
              continue;
            }

            logger.info(`[Page Method] Processing work: ${work.title.slice(0, 20)}... (awemeId: ${work.awemeId}, index: ${workIndex})`);

            try {
              // 清空之前的数据
              latestHolder.comments = [];
              latestHolder.awemeId = '';

              // 点击"选择作品"按钮
              await page.click('button:has-text("选择作品")');
              await page.waitForTimeout(2000);

              // 找到弹窗中的作品图片列表
              const workImages = await page.$$('[role="dialog"] img[src*="douyinpic"], .douyin-creator-interactive-sidesheet-inner img[src*="douyinpic"]');
              logger.info(`[Page Method] Found ${workImages.length} work images in dialog`);

              if (workIndex < workImages.length) {
                // 点击对应索引的作品
                await workImages[workIndex].click();
                logger.info(`[Page Method] Clicked work image at index ${workIndex}`);

                // 等待评论 API 响应
                await page.waitForTimeout(4000);

                // 获取评论
                if (latestHolder.comments.length > 0) {
                  // 使用当前 work 的 awemeId
                  const comments = latestHolder.comments.map(c => ({
                    ...c,
                    videoId: work.awemeId,
                  }));
                  allWorkComments.push({
                    videoId: work.awemeId,
                    videoTitle: work.title,
                    videoCoverUrl: work.coverUrl,
                    comments,
                  });
                  logger.info(`[Page Method] Got ${comments.length} comments for ${work.awemeId}`);
                } else {
                  // 尝试从页面提取
                  const pageComments = await this.extractCommentsFromPage(page);
                  if (pageComments.length > 0) {
                    const comments = pageComments.map(c => ({ ...c, videoId: work.awemeId }));
                    allWorkComments.push({
                      videoId: work.awemeId,
                      videoTitle: work.title,
                      videoCoverUrl: work.coverUrl,
                      comments,
                    });
                    logger.info(`[Page Method] Extracted ${comments.length} comments from page`);
                  } else {
                    logger.warn(`[Page Method] No comments for ${work.awemeId}`);
                  }
                }
              } else {
                logger.warn(`[Page Method] Index ${workIndex} out of range, only ${workImages.length} images`);
                await page.keyboard.press('Escape');
              }

              await page.waitForTimeout(1000);
            } catch (e) {
              logger.warn(`[Page Method] Error for work ${work.awemeId}:`, e);
              await page.keyboard.press('Escape').catch(() => { });
              await page.waitForTimeout(500);
            }
          }
        }
      }

      logger.info(`[API Interception] Total result: ${allWorkComments.length} works with comments`);
      await context.close();
    } catch (error) {
      logger.error('[API Interception] Error:', error);
    } finally {
      await browser.close();
    }

    return allWorkComments;
  }


  /**
   * 直接调用评论 API 获取数据（支持分页获取所有评论）
   * 优先使用视频页面 API（获取全部评论），失败时才使用创作者 API
   */
  private async fetchCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
    // 优先尝试视频页面 API（获取全部评论）
    logger.info(`[DirectAPI] Fetching ALL comments for ${awemeId} via video page API...`);
    let comments = await this.fetchVideoPageCommentsApi(page, awemeId);

    if (comments.length > 0) {
      logger.info(`[DirectAPI] Got ${comments.length} comments via video page API`);
      return comments;
    }

    // 如果视频页面 API 失败，尝试创作者评论 API（可能只返回部分评论）
    logger.info(`[DirectAPI] Video page API returned 0 comments, trying creator API...`);
    comments = await this.fetchCreatorCommentsDirectApi(page, awemeId);

    return comments;
  }

  /**
   * 通过视频页面获取全部评论（主要方案）
   * 这个 API 能获取视频的所有评论，不仅仅是创作者回复过的
   */
  private async fetchVideoPageCommentsApi(page: Page, awemeId: string): Promise<CommentItem[]> {
    const comments: CommentItem[] = [];
    const maxPages = 50;
    let cursor = 0;
    let hasMore = true;
    let pageCount = 0;

    try {
      // 导航到视频页面
      logger.info(`[VideoPageAPI] Navigating to video page for ${awemeId}...`);
      await page.goto(`https://www.douyin.com/video/${awemeId}`, {
        waitUntil: 'domcontentloaded',
        timeout: 30000,
      });
      await page.waitForTimeout(2000);

      while (hasMore && pageCount < maxPages) {
        pageCount++;

        const data = await page.evaluate(async ({ videoId, cursorValue }) => {
          try {
            const url = `https://www.douyin.com/aweme/v1/web/comment/list/?aweme_id=${videoId}&cursor=${cursorValue}&count=50&item_type=0&insert_ids=&whale_cut_token=&cut_version=1&rcFT=&aid=6383&device_platform=web_pc&verifyFp=&fp=&msToken=`;

            const resp = await fetch(url, {
              method: 'GET',
              credentials: 'include',
              headers: {
                'Accept': 'application/json, text/plain, */*',
                'Referer': `https://www.douyin.com/video/${videoId}`,
              },
            });

            if (!resp.ok) {
              return { error: `HTTP ${resp.status}`, comments: [] };
            }

            return resp.json();
          } catch (e) {
            return { error: String(e), comments: [] };
          }
        }, { videoId: awemeId, cursorValue: cursor });

        if (data?.error) {
          logger.warn(`[VideoPageAPI] API error for ${awemeId}: ${data.error}`);
        }

        if (data?.comments && Array.isArray(data.comments)) {
          for (const c of data.comments) {
            comments.push({
              commentId: String(c.cid || ''),
              authorId: String(c.user?.uid || c.user?.sec_uid || ''),
              authorName: String(c.user?.nickname || '匿名'),
              authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
              content: String(c.text || ''),
              likeCount: Number(c.digg_count || 0),
              commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
              videoId: String(c.aweme_id || awemeId),
            });
          }
          logger.info(`[VideoPageAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
        }

        hasMore = data?.has_more === true || data?.has_more === 1;
        cursor = data?.cursor || cursor + 50;

        if (!data?.comments || data.comments.length === 0) {
          hasMore = false;
        }
      }

      logger.info(`[VideoPageAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
    } catch (e) {
      logger.warn(`[VideoPageAPI] Failed to fetch comments for ${awemeId}:`, e);
    }

    return comments;
  }

  /**
   * 创作者评论管理 API（备用方案）
   * 获取的是需要回复的评论
   */
  private async fetchCreatorCommentsDirectApi(page: Page, awemeId: string): Promise<CommentItem[]> {
    const comments: CommentItem[] = [];
    const maxPages = 50;
    let cursor = 0;
    let hasMore = true;
    let pageCount = 0;

    try {
      while (hasMore && pageCount < maxPages) {
        pageCount++;

        const data = await page.evaluate(async ({ videoId, cursorValue }) => {
          const url = `https://creator.douyin.com/web/api/third_party/aweme/api/comment/read/aweme/v1/web/comment/list/select/?aweme_id=${videoId}&cursor=${cursorValue}&count=50&comment_select_options=0&sort_options=0&channel_id=618&app_id=2906&aid=2906&device_platform=webapp`;

          const resp = await fetch(url, {
            credentials: 'include',
            headers: {
              'Accept': 'application/json',
            },
          });

          return resp.json();
        }, { videoId: awemeId, cursorValue: cursor });

        if (data?.comments && Array.isArray(data.comments)) {
          for (const c of data.comments) {
            comments.push({
              commentId: String(c.cid || ''),
              authorId: String(c.user?.uid || ''),
              authorName: String(c.user?.nickname || '匿名'),
              authorAvatar: c.user?.avatar_thumb?.url_list?.[0] || '',
              content: String(c.text || ''),
              likeCount: Number(c.digg_count || 0),
              commentTime: new Date(Number(c.create_time || 0) * 1000).toISOString(),
              videoId: String(c.aweme_id || awemeId),
            });
          }
          logger.info(`[CreatorAPI] Page ${pageCount}: got ${data.comments.length} comments for ${awemeId}`);
        }

        hasMore = data?.has_more === true || data?.has_more === 1;
        cursor = data?.cursor || cursor + 50;

        if (!data?.comments || data.comments.length === 0) {
          hasMore = false;
        }
      }

      logger.info(`[CreatorAPI] Total fetched ${comments.length} comments for ${awemeId} from ${pageCount} pages`);
    } catch (e) {
      logger.warn(`[CreatorAPI] Failed to fetch comments for ${awemeId}:`, e);
    }

    return comments;
  }

  /**
   * 直接调用抖音 API 获取作品列表
   * 使用新的 work_list 接口，支持分页加载
   * 返回作品列表和总作品数
   * 
   * 注意：需要先导航到作品管理页面才能正确调用 API
   */
  private async fetchWorksDirectApi(page: Page): Promise<{
    works: Array<{
      awemeId: string;
      title: string;
      coverUrl: string;
      commentCount: number;
      createTime?: number;
    }>;
    total: number;
  }> {
    const works: Array<{
      awemeId: string;
      title: string;
      coverUrl: string;
      commentCount: number;
      createTime?: number;
    }> = [];
    let totalCount = 0; // 从 API 获取的总作品数

    try {
      // 首先导航到作品管理页面，确保 API 有正确的上下文和权限
      const contentManageUrl = 'https://creator.douyin.com/creator-micro/content/manage';
      const currentUrl = page.url();

      if (!currentUrl.includes('/content/manage')) {
        logger.info(`[DirectAPI] Navigating to content manage page...`);
        await page.goto(contentManageUrl, {
          waitUntil: 'domcontentloaded',
          timeout: 30000,
        });
        await page.waitForTimeout(2000);

        // 检查是否需要登录
        const newUrl = page.url();
        if (newUrl.includes('login') || newUrl.includes('passport')) {
          logger.warn('[DirectAPI] Not logged in, cannot fetch works');
          return { works, total: 0 };
        }
      }

      let hasMore = true;
      let maxCursor = 0;
      let pageCount = 0;
      const maxPages = 20; // 最多加载20页，防止无限循环

      while (hasMore && pageCount < maxPages) {
        pageCount++;
        logger.info(`[DirectAPI] Fetching works page ${pageCount}, cursor: ${maxCursor}`);

        const data = await page.evaluate(async (cursor: number) => {
          // 使用新的 work_list API 接口
          // status: 0 表示获取全部已发布的作品
          // count: 每页获取数量
          const url = `https://creator.douyin.com/janus/douyin/creator/pc/work_list?status=0&scene=star_atlas&device_platform=android&count=20&max_cursor=${cursor}&cookie_enabled=true&browser_language=zh-CN&browser_platform=Win32&browser_name=Mozilla&browser_online=true&timezone_name=Asia%2FShanghai&aid=1128`;

          const resp = await fetch(url, {
            credentials: 'include',
            headers: {
              'Accept': 'application/json',
            },
          });

          return resp.json();
        }, maxCursor);

        // 获取作品数
        const awemeList = data?.aweme_list || [];
        logger.info(`[DirectAPI] API response: status_code=${data?.status_code}, has_more=${data?.has_more}, max_cursor=${data?.max_cursor}, aweme_list_length=${awemeList.length}`);

        // 检查 API 返回状态
        if (data?.status_code !== 0 && data?.status_code !== undefined) {
          logger.warn(`[DirectAPI] API returned error status_code: ${data.status_code}`);
          // status_code: 8 表示未授权，可能需要重新登录
          if (data.status_code === 8) {
            logger.warn('[DirectAPI] status_code 8: Not authorized, may need re-login');
          }
          break;
        }

        // 优先从第一个作品的 author.aweme_count 获取真实作品数（只在第一页获取）
        if (pageCount === 1 && awemeList.length > 0) {
          const firstAweme = awemeList[0];
          const authorAwemeCount = firstAweme?.author?.aweme_count;
          if (authorAwemeCount !== undefined && authorAwemeCount > 0) {
            totalCount = authorAwemeCount;
            logger.info(`[DirectAPI] Using author.aweme_count as total works: ${totalCount}`);
          }
        }

        // 解析 aweme_list 中的作品数据
        logger.info(`[DirectAPI] Page ${pageCount}: got ${awemeList.length} works from aweme_list`);

        for (const aweme of awemeList) {
          const awemeId = String(aweme.aweme_id || '');
          if (!awemeId) continue;

          // 从 statistics 中获取评论数
          const statistics = aweme.statistics || {};
          const commentCount = parseInt(String(statistics.comment_count || '0'), 10);

          // 获取标题：优先使用 item_title，其次使用 desc（描述）
          let title = aweme.item_title || '';
          if (!title) {
            // 从 desc 中提取标题（取第一行或前50个字符）
            const desc = aweme.desc || aweme.caption || '';
            title = desc.split('\n')[0].slice(0, 50) || '无标题';
          }

          // 获取封面 URL：从 Cover.url_list 或 video.cover.url_list 中获取
          let coverUrl = '';
          if (aweme.Cover?.url_list?.length > 0) {
            coverUrl = aweme.Cover.url_list[0];
          } else if (aweme.video?.cover?.url_list?.length > 0) {
            coverUrl = aweme.video.cover.url_list[0];
          }

          works.push({
            awemeId,
            title,
            coverUrl,
            commentCount,
            createTime: aweme.create_time,
          });
        }

        // 检查是否有更多数据
        // 注意: 抖音 API 返回的 has_more 可能不准确，我们额外判断
        const apiHasMore = data?.has_more === true || data?.has_more === 1;

        // 更新游标：使用返回的 max_cursor
        if (data?.max_cursor !== undefined && data?.max_cursor !== null) {
          // 只有当 max_cursor 有变化时才继续
          if (data.max_cursor !== maxCursor) {
            maxCursor = data.max_cursor;
            hasMore = apiHasMore && awemeList.length > 0;
          } else {
            // max_cursor 没变化，说明到底了
            hasMore = false;
          }
        } else if (awemeList.length > 0) {
          // 如果没有 max_cursor，使用最后一个作品的 create_time 作为游标
          const lastAweme = awemeList[awemeList.length - 1];
          if (lastAweme.create_time) {
            const newCursor = lastAweme.create_time;
            if (newCursor !== maxCursor) {
              maxCursor = newCursor;
              hasMore = apiHasMore;
            } else {
              hasMore = false;
            }
          } else {
            hasMore = false;
          }
        } else {
          // 没有获取到数据，停止循环
          hasMore = false;
        }

        logger.info(`[DirectAPI] Page ${pageCount} result: got ${awemeList.length} works, hasMore=${hasMore}, nextCursor=${maxCursor}`);

        // 稍微延迟，避免请求过快
        if (hasMore) {
          await new Promise(resolve => setTimeout(resolve, 500));
        }
      }

      logger.info(`[DirectAPI] Total fetched ${works.length} works from ${pageCount} pages, items count: ${totalCount}`);
    } catch (e) {
      logger.warn('[DirectAPI] Failed to fetch works:', e);
    }

    return { works, total: totalCount };
  }

  /**
   * 通过 Python API 获取评论 - 分作品逐个获取
   */
  private async fetchCommentsViaPythonApi(platform: 'douyin' | 'xiaohongshu', cookies: CookieData[]): Promise<WorkComments[]> {
    const allWorkComments: WorkComments[] = [];
    const cookieString = JSON.stringify(cookies);

    // 1. 先获取作品列表
    logger.info(`[${platform} Comments Python] Fetching works list...`);
    const worksResponse = await fetch(`${PYTHON_SERVICE_URL}/works`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        platform,
        cookie: cookieString,
        page: 0,
        page_size: 50,
      }),
    });

    if (!worksResponse.ok) {
      throw new Error(`Python API works returned ${worksResponse.status}`);
    }

    const worksResult = await worksResponse.json();
    if (!worksResult.success) {
      throw new Error(worksResult.error || 'Failed to get works');
    }

    const works = worksResult.works || [];
    logger.info(`[${platform} Comments Python] Got ${works.length} works`);

    // 2. 遍历作品获取评论
    for (const work of works) {
      const workId = work.work_id;
      if (!workId) continue;

      try {
        logger.info(`[${platform} Comments Python] Fetching comments for work ${workId}...`);
        const commentsResponse = await fetch(`${PYTHON_SERVICE_URL}/comments`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            platform,
            cookie: cookieString,
            work_id: workId,
          }),
        });

        if (!commentsResponse.ok) {
          logger.warn(`[${platform} Comments Python] Comments API returned ${commentsResponse.status} for work ${workId}`);
          continue;
        }

        const commentsResult = await commentsResponse.json();
        if (!commentsResult.success) {
          logger.warn(`[${platform} Comments Python] Failed to get comments for work ${workId}: ${commentsResult.error}`);
          continue;
        }

        const comments: CommentItem[] = (commentsResult.comments || []).map((c: {
          comment_id: string;
          author_id: string;
          author_name: string;
          author_avatar: string;
          content: string;
          like_count: number;
          create_time: string;
          reply_count?: number;
        }) => ({
          commentId: c.comment_id,
          authorId: c.author_id,
          authorName: c.author_name,
          authorAvatar: c.author_avatar,
          content: c.content,
          likeCount: c.like_count,
          commentTime: c.create_time,
          replyCount: c.reply_count || 0,
        }));

        if (comments.length > 0) {
          allWorkComments.push({
            videoId: workId,
            videoTitle: work.title || '',
            videoCoverUrl: work.cover_url || '',
            comments,
          });
          logger.info(`[${platform} Comments Python] Got ${comments.length} comments for work ${workId}`);
        }
      } catch (commentError) {
        logger.warn(`[${platform} Comments Python] Error fetching comments for work ${workId}:`, commentError);
      }
    }

    logger.info(`[${platform} Comments Python] Total: ${allWorkComments.length} works with comments`);
    return allWorkComments;
  }

  /**
   * 通过 Python API 获取抖音评论 - 一次性获取所有作品的评论（备用）
   */
  private async fetchDouyinCommentsViaPythonApi(cookies: CookieData[]): Promise<WorkComments[]> {
    const cookieString = JSON.stringify(cookies);

    logger.info('[Douyin Comments Python] Fetching all comments...');
    const response = await fetch(`${PYTHON_SERVICE_URL}/all_comments`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        platform: 'douyin',
        cookie: cookieString,
      }),
    });

    if (!response.ok) {
      throw new Error(`Python API all_comments returned ${response.status}`);
    }

    const result = await response.json();
    if (!result.success) {
      throw new Error(result.error || 'Failed to get all comments');
    }

    const workComments = result.work_comments || [];
    logger.info(`[Douyin Comments Python] Got ${workComments.length} works with comments`);

    // 转换数据格式
    const allWorkComments: WorkComments[] = workComments.map((wc: {
      work_id: string;
      title: string;
      cover_url: string;
      comments: Array<{
        comment_id: string;
        author_id: string;
        author_name: string;
        author_avatar: string;
        content: string;
        like_count: number;
        create_time: string;
        is_author?: boolean;
      }>;
    }) => ({
      videoId: wc.work_id,
      videoTitle: wc.title || '',
      videoCoverUrl: wc.cover_url || '',
      comments: (wc.comments || []).map(c => ({
        commentId: c.comment_id,
        authorId: c.author_id,
        authorName: c.author_name,
        authorAvatar: c.author_avatar,
        content: c.content,
        likeCount: c.like_count,
        commentTime: c.create_time,
      })),
    }));

    logger.info(`[Douyin Comments Python] Total: ${allWorkComments.length} works with comments`);
    return allWorkComments;
  }

  /**
   * 获取抖音评论 - 优先使用 Python API
   */
  async fetchDouyinCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
    // 优先使用 Python API（分作品获取）
    const pythonAvailable = await this.checkPythonServiceAvailable();
    if (pythonAvailable) {
      logger.info('[Douyin Comments] Using Python API...');
      try {
        const result = await this.fetchCommentsViaPythonApi('douyin', cookies);
        if (result.length > 0) {
          return result;
        }
        logger.info('[Douyin Comments] Python API returned empty, falling back to Playwright...');
      } catch (pythonError) {
        logger.warn('[Douyin Comments] Python API failed:', pythonError);
      }
    }

    // 回退到 Playwright API 拦截方式
    const result = await this.fetchDouyinCommentsByApiInterception(cookies);
    if (result.length > 0) {
      return result;
    }

    // 如果 API 方式失败，使用旧的 DOM 解析方式作为备用
    logger.info('[Fallback] Using DOM parsing method...');

    const browser = await chromium.launch({
      headless: true, // 改为无头模式
      args: ['--no-sandbox', '--disable-setuid-sandbox'],
    });

    const allWorkComments: WorkComments[] = [];

    try {
      const context = await browser.newContext({
        viewport: { width: 1920, height: 1080 },
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      });

      // 设置 Cookie
      const playwrightCookies = cookies.map(c => ({
        name: c.name,
        value: c.value,
        domain: c.domain || '.douyin.com',
        path: c.path || '/',
      }));
      await context.addCookies(playwrightCookies);
      logger.info(`Set ${playwrightCookies.length} cookies`);

      const page = await context.newPage();

      // 导航到评论管理页面
      logger.info('Navigating to Douyin comment management page...');
      await page.goto('https://creator.douyin.com/creator-micro/interactive/comment', {
        waitUntil: 'domcontentloaded',
        timeout: 60000,
      });

      // 等待页面完全加载
      logger.info('Waiting for page to fully load...');
      await page.waitForTimeout(5000);

      // 检查是否需要登录
      const currentUrl = page.url();
      logger.info(`Current URL: ${currentUrl}`);
      if (currentUrl.includes('login') || currentUrl.includes('passport')) {
        logger.warn('Cookie expired, need re-login');
        await browser.close();
        return allWorkComments;
      }

      logger.info('Page loaded successfully');

      // 等待评论列表加载
      logger.info('Waiting for comments to load...');
      try {
        await page.waitForSelector('[class*="comment-content-text-"]', { timeout: 10000 });
        logger.info('Comments loaded');
      } catch {
        logger.warn('No comments found on initial load, will try to select works');
      }

      // 辅助函数：从当前页面提取评论
      const extractCommentsFromCurrentPage = async (): Promise<CommentItem[]> => {
        logger.info('Extracting comments from current page...');

        // 滚动页面加载所有评论
        await page.evaluate(async () => {
          // 滚动多次加载更多评论
          for (let i = 0; i < 10; i++) {
            window.scrollBy(0, 500);
            await new Promise(r => setTimeout(r, 800));
          }
          window.scrollTo(0, 0);
        });

        await page.waitForTimeout(2000);

        // 使用精确选择器提取评论
        const comments = await page.evaluate(() => {
          const result: Array<{
            commentId: string;
            authorId: string;
            authorName: string;
            authorAvatar: string;
            content: string;
            likeCount: number;
            commentTime: string;
          }> = [];

          const seenContents = new Set<string>();

          // 查找所有评论容器：包含 username 和 comment-content-text 的 container
          const allContainers = document.querySelectorAll('[class*="container-"]');
          const commentContainers: Element[] = [];

          allContainers.forEach(container => {
            const hasUsername = container.querySelector('[class*="username-"]');
            const hasCommentContent = container.querySelector('[class*="comment-content-text-"]');
            if (hasUsername && hasCommentContent) {
              commentContainers.push(container);
            }
          });

          console.log(`Found ${commentContainers.length} comment containers`);

          commentContainers.forEach((container, index) => {
            try {
              // 用户名
              const usernameEl = container.querySelector('[class*="username-"]');
              const authorName = usernameEl?.textContent?.trim() || '未知用户';

              // 时间
              const timeEl = container.querySelector('[class*="time-"]');
              const commentTime = timeEl?.textContent?.trim() || '';

              // 评论内容
              const contentEl = container.querySelector('[class*="comment-content-text-"]');
              const content = contentEl?.textContent?.trim() || '';

              if (!content) return;

              // 头像
              const avatarContainer = container.querySelector('[class*="avatar-"]');
              const avatarImg = avatarContainer?.querySelector('img');
              const authorAvatar = avatarImg?.src || '';

              // 去重
              const key = `${authorName}||${content}`;
              if (seenContents.has(key)) return;
              seenContents.add(key);

              // 点赞数
              let likeCount = 0;
              const opsEl = container.querySelector('[class*="operations-"]');
              if (opsEl) {
                const itemEl = opsEl.querySelector('[class*="item-"]');
                if (itemEl) {
                  const match = itemEl.textContent?.match(/(\d+)/);
                  if (match) likeCount = parseInt(match[1], 10);
                }
              }

              // 生成 ID
              const hash = content.slice(0, 30) + authorName + commentTime;
              const commentId = `dy_${btoa(encodeURIComponent(hash)).slice(0, 20)}`;

              result.push({
                commentId,
                authorId: authorName,
                authorName,
                authorAvatar,
                content,
                likeCount,
                commentTime,
              });

              console.log(`[${index}] ${authorName}: ${content.slice(0, 30)}`);
            } catch (e) {
              console.error(`Error at ${index}:`, e);
            }
          });

          return result;
        });

        logger.info(`Extracted ${comments.length} comments`);
        return comments;
      };

      // 辅助函数：获取当前显示的作品标题
      const getCurrentWorkTitle = async (): Promise<string> => {
        return page.evaluate(() => {
          // 查找作品标题 - 通常在页面顶部区域
          // 排除筛选器和按钮中的文本
          const excludeTexts = ['全部评论', '最新发布', '全部人群', '搜索', '选择作品', '评论管理'];

          // 方法1: 查找视频信息区域
          const videoInfoSelectors = [
            '[class*="video-info"] [class*="title"]',
            '[class*="work-info"] [class*="title"]',
            '[class*="content-info"] [class*="title"]',
          ];

          for (const selector of videoInfoSelectors) {
            const el = document.querySelector(selector);
            if (el?.textContent) {
              const text = el.textContent.trim();
              if (text.length > 5 && !excludeTexts.some(e => text.includes(e))) {
                return text;
              }
            }
          }

          // 方法2: 查找页面上较长的标题文本
          const allTexts = document.querySelectorAll('div, span, p');
          for (const el of Array.from(allTexts)) {
            const text = el.textContent?.trim() || '';
            if (text.length > 20 &&
              text.length < 200 &&
              !excludeTexts.some(e => text.includes(e)) &&
              !el.closest('button') &&
              !el.closest('[class*="select"]') &&
              !el.closest('[class*="filter"]')) {
              // 检查是否可能是作品标题（通常包含特定字符或格式）
              if (text.includes('#') || text.match(/[，。！？、]/)) {
                return text;
              }
            }
          }

          return '';
        });
      };

      // 步骤1: 先获取当前页面显示的评论（默认显示的第一个作品）
      logger.info('Step 1: Getting comments from default view...');
      const defaultTitle = await getCurrentWorkTitle();
      const defaultComments = await extractCommentsFromCurrentPage();

      if (defaultComments.length > 0) {
        allWorkComments.push({
          videoId: `video_${Date.now()}`,
          videoTitle: defaultTitle || '默认作品',
          videoCoverUrl: '',
          comments: defaultComments,
        });
        logger.info(`Got ${defaultComments.length} comments from default view, title: "${defaultTitle.slice(0, 50)}"`);
      }

      // 步骤2: 尝试点击"选择作品"按钮获取更多作品的评论
      logger.info('Step 2: Looking for "选择作品" button...');

      // 使用 locator 查找按钮
      const selectBtn = page.locator('text=选择作品').first();
      const btnCount = await selectBtn.count();
      logger.info(`Found ${btnCount} "选择作品" button(s)`);

      if (btnCount > 0) {
        logger.info('Clicking "选择作品" button...');
        await selectBtn.click();

        // 等待更长时间，确保弹窗完全加载
        logger.info('Waiting for work list modal to appear...');
        await page.waitForTimeout(5000);

        // 打印当前页面状态，帮助调试
        const modalInfo = await page.evaluate(() => {
          // 查找所有可能的弹窗元素
          const modals = document.querySelectorAll('[class*="modal"], [class*="popup"], [class*="drawer"], [class*="dialog"], [role="dialog"]');
          const modalClasses = Array.from(modals).map(m => m.className).slice(0, 5);

          // 查找所有图片（作品封面）
          const images = document.querySelectorAll('img[src*="douyinpic"]');

          // 查找所有可能的卡片元素
          const cards = document.querySelectorAll('[class*="card"], [class*="item"]');
          const cardClasses = Array.from(cards).map(c => c.className).slice(0, 10);

          return {
            modalCount: modals.length,
            modalClasses,
            imageCount: images.length,
            cardCount: cards.length,
            cardClasses,
          };
        });

        logger.info(`Modal debug: ${JSON.stringify(modalInfo)}`);

        // 尝试多种选择器查找作品列表
        const workSelectors = [
          '[class*="video-card"]',
          '[class*="work-item"]',
          '[class*="content-item"]',
          '[class*="modal"] [class*="card"]',
          '[class*="modal"] img',
          '[class*="drawer"] [class*="card"]',
          '[class*="drawer"] img',
          '[role="dialog"] [class*="card"]',
          '[role="dialog"] img',
          '[class*="popup"] img',
          'img[src*="douyinpic"]', // 直接找抖音图片
        ];

        let workElements: Awaited<ReturnType<typeof page.$$>> = [];
        let usedSelector = '';

        for (const selector of workSelectors) {
          const elements = await page.$$(selector);
          logger.info(`Selector "${selector}" found ${elements.length} elements`);
          if (elements.length > 0 && elements.length < 50) { // 避免选中太多无关元素
            workElements = elements;
            usedSelector = selector;
            break;
          }
        }

        logger.info(`Using selector "${usedSelector}", found ${workElements.length} work items`);

        if (workElements.length > 0) {
          // 首先获取所有作品的评论数信息
          // 根据 HTML 结构：
          // - 作品项容器: div.container-Lkxos9 (类名可能变化，使用 [class*="container-"])
          // - 标题: div.title-LUOP3b (类名可能变化，使用 [class*="title-"])
          // - 评论数: div.right-os7ZB9 > div (类名可能变化，使用 [class*="right-"] > div)
          const workInfoList = await page.evaluate(() => {
            const works: Array<{ index: number; title: string; commentCount: number }> = [];

            // 查找作品列表容器中的所有作品项
            // 根据用户提供的 HTML，作品项的类名是 container-Lkxos9
            const workContainers = document.querySelectorAll('[role="dialog"] [class*="container-"]');

            console.log(`Found ${workContainers.length} work containers`);

            workContainers.forEach((container, index) => {
              // 检查是否包含图片（确认是作品项而不是其他容器）
              const img = container.querySelector('img[src*="douyinpic"]');
              if (!img) {
                console.log(`Container ${index} has no douyinpic image, skipping`);
                return;
              }

              // 提取标题
              const titleEl = container.querySelector('[class*="title-"]');
              const title = titleEl?.textContent?.trim() || `作品 ${works.length + 1}`;

              // 提取评论数 - 在 right- 容器的最后一个 div 中
              let commentCount = 0;
              const rightContainer = container.querySelector('[class*="right-"]');
              if (rightContainer) {
                // 获取 right 容器下的所有直接 div 子元素
                const divs = rightContainer.querySelectorAll(':scope > div');
                if (divs.length > 0) {
                  // 最后一个 div 包含评论数
                  const lastDiv = divs[divs.length - 1];
                  const text = lastDiv.textContent?.trim() || '0';
                  const num = parseInt(text, 10);
                  if (!isNaN(num)) {
                    commentCount = num;
                  }
                }
              }

              console.log(`Work ${works.length}: title="${title.slice(0, 30)}...", commentCount=${commentCount}`);

              works.push({
                index: works.length,
                title: title.slice(0, 100),
                commentCount
              });
            });

            // 如果上面的选择器没找到，尝试备用方法
            if (works.length === 0) {
              console.log('Primary selector failed, trying fallback...');
              // 直接查找包含 douyinpic 图片的元素的父容器
              const images = document.querySelectorAll('[role="dialog"] img[src*="douyinpic"]');
              images.forEach((img, index) => {
                // 向上查找到作品项容器
                let container = img.parentElement;
                while (container && !container.classList.toString().includes('container-')) {
                  container = container.parentElement;
                }

                if (container) {
                  const titleEl = container.querySelector('[class*="title-"]');
                  const title = titleEl?.textContent?.trim() || `作品 ${index + 1}`;

                  // 查找评论数
                  let commentCount = 0;
                  const rightEl = container.querySelector('[class*="right-"]');
                  if (rightEl) {
                    const text = rightEl.textContent?.trim() || '';
                    // 提取最后出现的数字
                    const matches = text.match(/\d+/g);
                    if (matches && matches.length > 0) {
                      commentCount = parseInt(matches[matches.length - 1], 10);
                    }
                  }

                  works.push({ index, title: title.slice(0, 100), commentCount });
                }
              });
            }

            return works;
          });

          logger.info(`Work info list (${workInfoList.length} items): ${JSON.stringify(workInfoList)}`);

          // 过滤出评论数 > 0 的作品，或者评论数未知（-1）的作品
          const worksWithComments = workInfoList.filter(w => w.commentCount > 0 || w.commentCount === -1);
          logger.info(`Found ${worksWithComments.length} works with comments > 0 or unknown (out of ${workInfoList.length})`);

          // 如果所有作品评论数都是0，则不处理任何作品
          const allZero = workInfoList.every(w => w.commentCount === 0);
          if (allZero) {
            logger.info('All works have 0 comments, skipping all');
          }

          // 如果没有找到评论数信息或有未知的，处理这些作品
          const indicesToProcess = allZero
            ? []
            : (worksWithComments.length > 0
              ? worksWithComments.map(w => w.index)
              : Array.from({ length: Math.min(workElements.length, 10) }, (_, i) => i));

          logger.info(`Will process work indices: ${indicesToProcess.join(', ')}`);

          // 遍历每个有评论的作品
          for (let idx = 0; idx < indicesToProcess.length; idx++) {
            const i = indicesToProcess[idx];
            try {
              const workInfo = workInfoList.find(w => w.index === i);
              logger.info(`Processing work ${idx + 1}/${indicesToProcess.length} (index=${i}, title="${workInfo?.title}", expectedComments=${workInfo?.commentCount})...`);

              // 重新打开选择作品弹窗
              if (idx > 0) {
                await selectBtn.click();
                await page.waitForTimeout(3000);
              }

              // 重新获取元素列表（因为 DOM 可能已变化）
              const currentItems = await page.$$(usedSelector);
              if (i < currentItems.length) {
                // 滚动到元素可见
                await currentItems[i].scrollIntoViewIfNeeded();
                await page.waitForTimeout(500);

                // 点击元素
                await currentItems[i].click();
                await page.waitForTimeout(4000);

                // 获取评论
                const title = await getCurrentWorkTitle();
                const comments = await extractCommentsFromCurrentPage();

                logger.info(`Work index=${i}: title="${title.slice(0, 50)}", comments=${comments.length}`);

                // 检查是否已经获取过这个作品的评论
                const exists = allWorkComments.some(w =>
                  w.videoTitle === title ||
                  (w.comments.length > 0 && comments.length > 0 &&
                    w.comments[0].content === comments[0].content)
                );

                if (!exists && (comments.length > 0 || title)) {
                  allWorkComments.push({
                    videoId: `video_${Date.now()}_${i}`,
                    videoTitle: title || workInfo?.title || `作品 ${i + 1}`,
                    videoCoverUrl: '',
                    comments,
                  });
                  logger.info(`Work index=${i}: Saved ${comments.length} comments`);
                } else {
                  logger.info(`Work index=${i}: Skipped (duplicate or empty)`);
                }
              }
            } catch (err) {
              logger.warn(`Error processing work index=${i}:`, err);
            }
          }
        } else {
          logger.warn('No work items found in modal');
        }

        // 按 Escape 关闭弹窗
        try {
          await page.keyboard.press('Escape');
          await page.waitForTimeout(500);
        } catch { }
      } else {
        logger.warn('"选择作品" button not found, only default comments will be returned');
      }

      await page.close();
      await context.close();
      await browser.close();

      const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
      logger.info(`Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);

      return allWorkComments;

    } catch (error) {
      logger.error('Error fetching Douyin comments:', error);
      try {
        await browser.close();
      } catch { }
      return allWorkComments;
    }
  }

  /**
   * 通过 Python API 获取小红书评论 - 一次性获取所有作品的评论
   */
  private async fetchXiaohongshuCommentsViaPythonApi(cookies: CookieData[]): Promise<WorkComments[]> {
    const cookieString = JSON.stringify(cookies);

    logger.info('[Xiaohongshu Comments Python] Fetching all comments...');
    const response = await fetch(`${PYTHON_SERVICE_URL}/all_comments`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        platform: 'xiaohongshu',
        cookie: cookieString,
      }),
    });

    if (!response.ok) {
      throw new Error(`Python API all_comments returned ${response.status}`);
    }

    const result = await response.json();
    if (!result.success) {
      throw new Error(result.error || 'Failed to get all comments');
    }

    const workComments = result.work_comments || [];
    logger.info(`[Xiaohongshu Comments Python] Got ${workComments.length} works with comments`);

    // 转换数据格式
    const allWorkComments: WorkComments[] = workComments.map((wc: {
      work_id: string;
      title: string;
      cover_url: string;
      comments: Array<{
        comment_id: string;
        author_id: string;
        author_name: string;
        author_avatar: string;
        content: string;
        like_count: number;
        create_time: string;
      }>;
    }) => ({
      videoId: wc.work_id,
      videoTitle: wc.title || '',
      videoCoverUrl: wc.cover_url || '',
      comments: (wc.comments || []).map(c => ({
        commentId: c.comment_id,
        authorId: c.author_id,
        authorName: c.author_name,
        authorAvatar: c.author_avatar,
        content: c.content,
        likeCount: c.like_count,
        commentTime: c.create_time,
      })),
    }));

    logger.info(`[Xiaohongshu Comments Python] Total: ${allWorkComments.length} works with comments`);
    return allWorkComments;
  }

  /**
   * 获取小红书评论 - 优先使用 Python API
   */
  async fetchXiaohongshuCommentsViaApi(cookies: CookieData[]): Promise<WorkComments[]> {
    // 优先使用 Python API（分作品获取）
    const pythonAvailable = await this.checkPythonServiceAvailable();
    if (pythonAvailable) {
      logger.info('[Xiaohongshu Comments] Using Python API...');
      try {
        const result = await this.fetchCommentsViaPythonApi('xiaohongshu', cookies);
        if (result.length > 0) {
          return result;
        }
        logger.info('[Xiaohongshu Comments] Python API returned empty, falling back to Playwright...');
      } catch (pythonError) {
        logger.warn('[Xiaohongshu Comments] Python API failed:', pythonError);
      }
    }

    // 回退到 Playwright 方式
    const browser = await chromium.launch({
      headless: true,
      args: ['--no-sandbox', '--disable-setuid-sandbox'],
    });

    const allWorkComments: WorkComments[] = [];

    try {
      const context = await browser.newContext({
        viewport: { width: 1920, height: 1080 },
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      });

      // 设置 Cookie
      const playwrightCookies = cookies.map(c => ({
        name: c.name,
        value: c.value,
        domain: c.domain || '.xiaohongshu.com',
        path: c.path || '/',
      }));
      await context.addCookies(playwrightCookies);
      logger.info(`[Xiaohongshu Comments] Set ${playwrightCookies.length} cookies`);

      const page = await context.newPage();

      // 用于捕获评论数据
      const capturedComments: Map<string, CommentItem[]> = new Map();
      const capturedNotes: Array<{
        noteId: string;
        title: string;
        coverUrl: string;
      }> = [];

      // 设置 API 响应监听器
      page.on('response', async (response) => {
        const url = response.url();
        try {
          // 监听笔记列表 API
          if (url.includes('/api/galaxy/creator/content/note_list') ||
            url.includes('/api/galaxy/creator/notes')) {
            const data = await response.json();
            logger.info(`[Xiaohongshu API] Notes list: ${JSON.stringify(data).slice(0, 500)}`);
            const notes = data?.data?.notes || data?.data?.list || [];
            for (const note of notes) {
              capturedNotes.push({
                noteId: note.note_id || note.id || '',
                title: note.title || note.desc || '',
                coverUrl: note.cover?.url || note.cover || '',
              });
            }
          }

          // 监听评论列表 API
          if (url.includes('/api/sns/web/v2/comment/page') ||
            url.includes('/api/galaxy/creator/comment') ||
            url.includes('/api/sns/v1/note/comment')) {
            const data = await response.json();
            logger.info(`[Xiaohongshu API] Comments: ${JSON.stringify(data).slice(0, 500)}`);

            const comments: CommentItem[] = [];
            const commentList = data?.data?.comments || data?.comments || [];

            for (const comment of commentList) {
              comments.push({
                commentId: comment.id || comment.comment_id || `xhs_${Date.now()}`,
                authorId: comment.user_info?.user_id || comment.user_id || '',
                authorName: comment.user_info?.nickname || comment.nickname || '',
                authorAvatar: comment.user_info?.image || comment.avatar || '',
                content: comment.content || '',
                likeCount: comment.like_count || 0,
                commentTime: comment.create_time || comment.time || '',
                parentCommentId: comment.target_comment_id || undefined,
              });

              // 处理子评论
              const subComments = comment.sub_comments || comment.replies || [];
              for (const sub of subComments) {
                comments.push({
                  commentId: sub.id || sub.comment_id || `xhs_sub_${Date.now()}`,
                  authorId: sub.user_info?.user_id || sub.user_id || '',
                  authorName: sub.user_info?.nickname || sub.nickname || '',
                  authorAvatar: sub.user_info?.image || sub.avatar || '',
                  content: sub.content || '',
                  likeCount: sub.like_count || 0,
                  commentTime: sub.create_time || sub.time || '',
                  parentCommentId: comment.id || comment.comment_id || undefined,
                });
              }
            }

            // 尝试从 URL 获取笔记 ID
            const noteIdMatch = url.match(/note_id=([^&]+)/) || url.match(/noteId=([^&]+)/);
            const noteId = noteIdMatch?.[1] || `note_${Date.now()}`;

            if (comments.length > 0) {
              const existing = capturedComments.get(noteId) || [];
              capturedComments.set(noteId, [...existing, ...comments]);
            }
          }
        } catch { }
      });

      // 导航到评论管理页面
      logger.info('[Xiaohongshu Comments] Navigating to comment management...');
      await page.goto('https://creator.xiaohongshu.com/creator/comment', {
        waitUntil: 'domcontentloaded',
        timeout: 60000,
      });

      await page.waitForTimeout(5000);

      // 检查是否需要登录
      const currentUrl = page.url();
      if (currentUrl.includes('login') || currentUrl.includes('passport')) {
        logger.warn('[Xiaohongshu Comments] Cookie expired, need re-login');
        await browser.close();
        return allWorkComments;
      }

      // 尝试加载更多评论
      for (let i = 0; i < 5; i++) {
        await page.evaluate(() => {
          window.scrollBy(0, 500);
        });
        await page.waitForTimeout(1000);
      }

      // 等待 API 响应
      await page.waitForTimeout(3000);

      // 将捕获的评论转换为 WorkComments 格式
      for (const [noteId, comments] of capturedComments) {
        const noteInfo = capturedNotes.find(n => n.noteId === noteId);
        allWorkComments.push({
          videoId: noteId,
          videoTitle: noteInfo?.title || `笔记 ${noteId.slice(0, 10)}`,
          videoCoverUrl: noteInfo?.coverUrl || '',
          comments,
        });
      }

      // 如果没有从 API 获取到评论，尝试从页面提取
      if (allWorkComments.length === 0) {
        logger.info('[Xiaohongshu Comments] No comments from API, extracting from page...');

        const pageComments = await page.evaluate(() => {
          const result: Array<{
            commentId: string;
            authorName: string;
            authorAvatar: string;
            content: string;
            likeCount: number;
            commentTime: string;
          }> = [];

          const commentItems = document.querySelectorAll('[class*="comment-item"], [class*="comment-card"]');
          commentItems.forEach((item, index) => {
            try {
              const authorEl = item.querySelector('[class*="author"], [class*="name"]');
              const avatarEl = item.querySelector('img');
              const contentEl = item.querySelector('[class*="content"]');
              const timeEl = item.querySelector('[class*="time"]');
              const likeEl = item.querySelector('[class*="like"] span');

              result.push({
                commentId: `xhs_page_${index}`,
                authorName: authorEl?.textContent?.trim() || '',
                authorAvatar: avatarEl?.src || '',
                content: contentEl?.textContent?.trim() || '',
                likeCount: parseInt(likeEl?.textContent || '0') || 0,
                commentTime: timeEl?.textContent?.trim() || '',
              });
            } catch { }
          });

          return result;
        });

        if (pageComments.length > 0) {
          allWorkComments.push({
            videoId: 'page_comments',
            videoTitle: '页面评论',
            videoCoverUrl: '',
            comments: pageComments.map(c => ({
              ...c,
              authorId: '',
            })),
          });
        }
      }

      await page.close();
      await context.close();
      await browser.close();

      const totalComments = allWorkComments.reduce((sum, w) => sum + w.comments.length, 0);
      logger.info(`[Xiaohongshu Comments] Total: fetched ${totalComments} comments from ${allWorkComments.length} works`);

      return allWorkComments;

    } catch (error) {
      logger.error('[Xiaohongshu Comments] Error:', error);
      try {
        await browser.close();
      } catch { }
      return allWorkComments;
    }
  }
}

export const headlessBrowserService = new HeadlessBrowserService();
