/**
 * 抖音登录服务
 * @module services/login/DouyinLoginService
 * 
 * 登录流程（按用户要求）：
 * 1. 打开 https://creator.douyin.com/
 * 2. 等待用户扫码登录，跳转到 /creator-micro/home 或 AI 识别已登录
 * 3. 从页面 HTML 提取：头像、昵称、抖音号、粉丝数、关注数、获赞数
 * 4. 跳转到 https://creator.douyin.com/creator-micro/content/manage 作品管理页
 * 5. 监听 API /janus/douyin/creator/pc/work_list 获取作品列表，取 items 数量作为作品数
 * 6. 完成后发送事件，账号ID使用 dy_ 前缀
 */

import type { Page } from 'playwright';
import { logger } from '../../utils/logger.js';
import { BaseLoginService, type ApiInterceptConfig } from './BaseLoginService.js';
import type { AccountInfo, LoginSession } from './types.js';

export class DouyinLoginService extends BaseLoginService {
  constructor() {
    super({
      platform: 'douyin',
      displayName: '抖音',
      loginUrl: 'https://creator.douyin.com/',
      successIndicators: ['/creator-micro/home', 'creator.douyin.com/creator-micro'],
      cookieDomain: '.douyin.com',
      accountIdPrefix: 'dy_',
    });
  }

  /**
   * API 拦截配置 - 监听作品列表接口
   */
  protected override getApiInterceptConfigs(): ApiInterceptConfig[] {
    return [
      {
        urlPattern: '/janus/douyin/creator/pc/work_list',
        dataKey: 'workList',
        handler: (data: any) => {
          // 取 items 或 aweme_list 的数量作为作品数（不用 total）
          const items = data.items || data.aweme_list || [];
          return { items, count: items.length };
        },
      },
    ];
  }

  /**
   * 收集账号信息
   */
  protected override async collectAccountInfo(session: LoginSession): Promise<AccountInfo | null> {
    try {
      // 步骤3: 从首页 HTML 提取账号基本信息
      logger.info('[抖音] 提取页面账号信息...');
      const basicInfo = await this.extractInfoFromPage(session.page);

      if (!basicInfo.douyinId) {
        logger.error('[抖音] 无法获取抖音号');
        return null;
      }

      logger.info('[抖音] 基本信息:', basicInfo);

      // 步骤4+5: 跳转到作品管理页，等待 API 返回作品列表
      logger.info('[抖音] 跳转到作品管理页...');
      const worksUrl = 'https://creator.douyin.com/creator-micro/content/manage';
      const workListData = await this.navigateAndWaitForApi(session, worksUrl, 'workList', 15000);

      const worksCount = workListData?.count || 0;
      logger.info(`[抖音] 作品数: ${worksCount}`);

      // 步骤6: 组装账号信息，使用 dy_ 前缀
      return {
        accountId: `dy_${basicInfo.douyinId}`,
        accountName: basicInfo.nickname || '抖音用户',
        avatarUrl: basicInfo.avatar || '',
        fansCount: basicInfo.fansCount || 0,
        worksCount,
        followingCount: basicInfo.followingCount,
        likeCount: basicInfo.likeCount,
      };
    } catch (error) {
      logger.error('[抖音] 收集账号信息失败:', error);
      return null;
    }
  }

  /**
   * 从页面 HTML 提取账号信息
   * 
   * 页面 HTML 结构：
   * <div class="container-vEyGlK">
   *   <div class="avatar-XoPjK6"><img src="头像URL"></div>
   *   <div class="name-_lSSDc">昵称</div>
   *   <div class="unique_id-EuH8eA">抖音号：xxxxx</div>
   *   <div id="guide_home_following">关注 <span class="number-No6ev9">612</span></div>
   *   <div id="guide_home_fans">粉丝 <span class="number-No6ev9">64</span></div>
   *   <div class="statics-item-MDWoNA">获赞 <span class="number-No6ev9">3</span></div>
   * </div>
   */
  private async extractInfoFromPage(page: Page): Promise<{
    douyinId?: string;
    nickname?: string;
    avatar?: string;
    fansCount?: number;
    followingCount?: number;
    likeCount?: number;
  }> {
    return page.evaluate(() => {
      const result: any = {};

      // 解析数字（支持万、亿）
      const parseNum = (text: string): number => {
        const match = text.match(/(\d+(?:\.\d+)?)\s*(万|亿|w)?/i);
        if (!match) return 0;
        let num = parseFloat(match[1]);
        if (match[2] === '万' || match[2]?.toLowerCase() === 'w') num *= 10000;
        if (match[2] === '亿') num *= 100000000;
        return Math.floor(num);
      };

      // 头像
      const avatarImg = document.querySelector('.avatar-XoPjK6 img, [class*="avatar"] img') as HTMLImageElement;
      if (avatarImg?.src) result.avatar = avatarImg.src;

      // 昵称
      const nameEl = document.querySelector('.name-_lSSDc, [class*="name-"]');
      if (nameEl) result.nickname = nameEl.textContent?.trim();

      // 抖音号
      const idEl = document.querySelector('.unique_id-EuH8eA, [class*="unique_id"]');
      if (idEl) {
        const text = idEl.textContent || '';
        const match = text.match(/抖音号[：:]\s*(\S+)/);
        if (match) result.douyinId = match[1];
      }

      // 关注数
      const followingEl = document.querySelector('#guide_home_following');
      if (followingEl) {
        const numEl = followingEl.querySelector('[class*="number"]');
        if (numEl) result.followingCount = parseNum(numEl.textContent || '0');
      }

      // 粉丝数
      const fansEl = document.querySelector('#guide_home_fans');
      if (fansEl) {
        const numEl = fansEl.querySelector('[class*="number"]');
        if (numEl) result.fansCount = parseNum(numEl.textContent || '0');
      }

      // 获赞数
      const statsItems = document.querySelectorAll('.statics-item-MDWoNA, [class*="statics-item"]');
      statsItems.forEach(item => {
        if (item.textContent?.includes('获赞')) {
          const numEl = item.querySelector('[class*="number"]');
          if (numEl) result.likeCount = parseNum(numEl.textContent || '0');
        }
      });

      return result;
    });
  }
}

// 导出单例
export const douyinLoginService = new DouyinLoginService();
