/**
 * 登录服务管理器
 * @module services/login/LoginServiceManager
 * 
 * 统一管理和调度各平台的登录服务
 */

import { EventEmitter } from 'events';
import { logger } from '../../utils/logger.js';
import type { PlatformType } from '@media-manager/shared';
import type { BaseLoginService } from './BaseLoginService.js';
import type { LoginResultEvent, AIAnalysisEvent, VerificationNeededEvent, AccountInfo, LoginSessionStatus } from './types.js';

// 导入各平台登录服务
import { douyinLoginService } from './DouyinLoginService.js';
import { xiaohongshuLoginService } from './XiaohongshuLoginService.js';
import { weixinVideoLoginService } from './WeixinVideoLoginService.js';
import { baijiahaoLoginService } from './BaijiahaoLoginService.js';

/**
 * 支持的平台类型（用于登录）
 */
export type SupportedLoginPlatform = 'douyin' | 'xiaohongshu' | 'weixin' | 'weixin_video' | 'baijiahao';

/**
 * 登录服务管理器
 * 
 * @example
 * ```typescript
 * import { loginServiceManager } from './services/login';
 * 
 * // 启动登录会话
 * const { sessionId, message } = await loginServiceManager.startLoginSession('douyin', userId);
 * 
 * // 监听登录结果
 * loginServiceManager.on('loginResult', (event) => {
 *   console.log('登录结果:', event);
 *   // event.accountInfo 包含完整的账号信息
 *   // accountId 格式: dy_xxx, xhs_xxx, sph_xxx, bjh_xxx
 * });
 * 
 * // 取消会话
 * await loginServiceManager.cancelSession(sessionId);
 * ```
 */
export class LoginServiceManager extends EventEmitter {
  /** 平台服务映射 */
  private readonly services: Map<string, BaseLoginService>;

  constructor() {
    super();

    // 注册各平台服务
    this.services = new Map([
      ['douyin', douyinLoginService],
      ['xiaohongshu', xiaohongshuLoginService],
      ['weixin', weixinVideoLoginService],
      ['weixin_video', weixinVideoLoginService],
      ['baijiahao', baijiahaoLoginService],
    ]);

    // 转发各服务的事件
    this.setupEventForwarding();

    logger.info('[LoginManager] 已初始化，支持平台:', this.getSupportedPlatforms());
  }

  /**
   * 设置事件转发
   */
  private setupEventForwarding(): void {
    const processedServices = new Set<BaseLoginService>();

    for (const [, service] of this.services) {
      // 避免重复注册（weixin 和 weixin_video 共用同一个服务）
      if (processedServices.has(service)) continue;
      processedServices.add(service);

      // 转发登录结果事件
      service.on('loginResult', (event: LoginResultEvent) => {
        this.emit('loginResult', event);
      });

      // 转发 AI 分析事件
      service.on('aiAnalysis', (event: AIAnalysisEvent) => {
        this.emit('aiAnalysis', event);
      });

      // 转发验证需求事件
      service.on('verificationNeeded', (event: VerificationNeededEvent) => {
        this.emit('verificationNeeded', event);
      });
    }
  }

  /**
   * 获取平台对应的登录服务
   */
  private getService(platform: PlatformType): BaseLoginService | undefined {
    return this.services.get(platform);
  }

  /**
   * 检查平台是否支持登录
   */
  isSupportedPlatform(platform: PlatformType): boolean {
    return this.services.has(platform);
  }

  /**
   * 获取支持的平台列表
   */
  getSupportedPlatforms(): string[] {
    // 去重（weixin 和 weixin_video 算同一个）
    return ['douyin', 'xiaohongshu', 'weixin_video', 'baijiahao'];
  }

  /**
   * 获取平台显示名称
   */
  getPlatformDisplayName(platform: PlatformType): string {
    const displayNames: Record<string, string> = {
      douyin: '抖音',
      xiaohongshu: '小红书',
      weixin: '视频号',
      weixin_video: '视频号',
      baijiahao: '百家号',
    };
    return displayNames[platform] || platform;
  }

  /**
   * 开始登录会话
   * 
   * @param platform - 平台类型
   * @param userId - 可选的用户ID，用于 WebSocket 推送状态
   * @returns 会话信息
   * @throws Error 如果平台不支持
   */
  async startLoginSession(platform: PlatformType, userId?: number): Promise<{ sessionId: string; message: string }> {
    const service = this.getService(platform);
    
    if (!service) {
      throw new Error(`不支持的平台: ${platform}`);
    }

    logger.info(`[LoginManager] 启动登录会话: ${platform}, userId: ${userId}`);
    return service.startLoginSession(userId);
  }

  /**
   * 获取会话状态
   */
  getSessionStatus(sessionId: string): {
    status: LoginSessionStatus;
    cookies?: string;
    accountInfo?: AccountInfo;
    error?: string;
    userId?: number;
  } | null {
    const platform = this.extractPlatformFromSessionId(sessionId);
    if (!platform) return null;

    const service = this.getService(platform as PlatformType);
    return service?.getSessionStatus(sessionId) || null;
  }

  /**
   * 获取会话的用户ID
   */
  getSessionUserId(sessionId: string): number | undefined {
    const platform = this.extractPlatformFromSessionId(sessionId);
    if (!platform) return undefined;

    const service = this.getService(platform as PlatformType);
    return service?.getSessionUserId(sessionId);
  }

  /**
   * 取消登录会话
   */
  async cancelSession(sessionId: string): Promise<void> {
    const platform = this.extractPlatformFromSessionId(sessionId);
    if (!platform) {
      logger.warn(`[LoginManager] 无法解析会话ID: ${sessionId}`);
      return;
    }

    const service = this.getService(platform as PlatformType);
    if (service) {
      await service.cancelSession(sessionId);
    }
  }

  /**
   * 从会话ID中提取平台
   * 会话ID格式: login_{platform}_{timestamp}
   */
  private extractPlatformFromSessionId(sessionId: string): string | null {
    const match = sessionId.match(/^login_([^_]+)_\d+$/);
    return match ? match[1] : null;
  }

  /**
   * 清理指定平台的所有会话
   */
  async cleanupPlatform(platform: PlatformType): Promise<void> {
    const service = this.getService(platform);
    if (service) {
      await service.cleanup();
    }
  }

  /**
   * 清理所有会话
   */
  async cleanup(): Promise<void> {
    logger.info('[LoginManager] 清理所有登录会话');
    
    const cleanupPromises: Promise<void>[] = [];
    const processedServices = new Set<BaseLoginService>();

    for (const service of this.services.values()) {
      if (!processedServices.has(service)) {
        processedServices.add(service);
        cleanupPromises.push(service.cleanup());
      }
    }

    await Promise.all(cleanupPromises);
  }
}

// 导出单例
export const loginServiceManager = new LoginServiceManager();
