/**
 * 小红书登录服务
 * @module services/login/XiaohongshuLoginService
 * 
 * 登录流程（按用户要求）：
 * 1. 打开 https://creator.xiaohongshu.com/login
 * 2. 等待用户扫码登录，跳转到 /new/home 或 AI 识别已登录
 * 3. 监听 API /api/galaxy/creator/home/personal_info 获取：头像(avatar)、昵称(name)、小红书号(red_num)、粉丝数(fans_count)
 * 4. 跳转到 https://creator.xiaohongshu.com/new/note-manager 笔记管理页
 * 5. 监听 API /web_api/sns/v5/creator/note/user/posted 获取笔记列表，取 notes 数量作为作品数
 * 6. 完成后发送事件，账号ID使用 xhs_ 前缀
 */

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

export class XiaohongshuLoginService extends BaseLoginService {
  constructor() {
    super({
      platform: 'xiaohongshu',
      displayName: '小红书',
      loginUrl: 'https://creator.xiaohongshu.com/login',
      successIndicators: ['/new/home', 'creator.xiaohongshu.com/new'],
      cookieDomain: '.xiaohongshu.com',
      accountIdPrefix: 'xhs_',
    });
  }

  /**
   * API 拦截配置
   */
  protected override getApiInterceptConfigs(): ApiInterceptConfig[] {
    return [
      // 个人信息接口
      {
        urlPattern: '/api/galaxy/creator/home/personal_info',
        dataKey: 'personalInfo',
        handler: (data: any) => {
          const info = data.data || data;
          return {
            avatar: info.avatar,
            name: info.name,
            redNum: info.red_num,
            fansCount: info.fans_count,
          };
        },
      },
      // 笔记列表接口
      {
        urlPattern: '/web_api/sns/v5/creator/note/user/posted',
        dataKey: 'noteList',
        handler: (data: any) => {
          const notes = data.data?.notes || data.notes || [];
          return { notes, count: notes.length };
        },
      },
    ];
  }

  /**
   * 收集账号信息
   */
  protected override async collectAccountInfo(session: LoginSession): Promise<AccountInfo | null> {
    try {
      // 步骤3: 等待个人信息 API 数据
      logger.info('[小红书] 等待个人信息 API...');
      let personalInfo = await this.waitForApiData(session, 'personalInfo', 10000);

      // 如果没拿到，刷新页面重试
      if (!personalInfo) {
        logger.info('[小红书] 未拿到个人信息，刷新页面重试...');
        await session.page.reload({ waitUntil: 'domcontentloaded' });
        personalInfo = await this.waitForApiData(session, 'personalInfo', 10000);
      }

      if (!personalInfo?.redNum) {
        logger.error('[小红书] 无法获取小红书号');
        return null;
      }

      logger.info('[小红书] 个人信息:', personalInfo);

      // 步骤4+5: 跳转到笔记管理页，等待笔记列表 API
      logger.info('[小红书] 跳转到笔记管理页...');
      const notesUrl = 'https://creator.xiaohongshu.com/new/note-manager';
      const noteListData = await this.navigateAndWaitForApi(session, notesUrl, 'noteList', 15000);

      const worksCount = noteListData?.count || 0;
      logger.info(`[小红书] 笔记数: ${worksCount}`);

      // 步骤6: 组装账号信息，使用 xhs_ 前缀
      return {
        accountId: `xhs_${personalInfo.redNum}`,
        accountName: personalInfo.name || '小红书用户',
        avatarUrl: personalInfo.avatar || '',
        fansCount: personalInfo.fansCount || 0,
        worksCount,
      };
    } catch (error) {
      logger.error('[小红书] 收集账号信息失败:', error);
      return null;
    }
  }
}

// 导出单例
export const xiaohongshuLoginService = new XiaohongshuLoginService();
