import { chromium, type Browser } from 'playwright';
import { logger } from '../utils/logger.js';

export interface BrowserOptions {
  headless?: boolean;
}

/**
 * 浏览器管理器
 * 支持有头和无头两种模式的浏览器实例
 */
export class BrowserManager {
  // 有头浏览器（用于用户交互，如登录）
  private static headfulBrowser: Browser | null = null;
  private static isHeadfulInitializing = false;
  
  // 无头浏览器（用于后台任务，如发布视频）
  private static headlessBrowser: Browser | null = null;
  private static isHeadlessInitializing = false;
  
  /**
   * 获取浏览器实例
   * @param options.headless 是否使用无头模式，默认 false
   */
  static async getBrowser(options?: BrowserOptions): Promise<Browser> {
    const headless = options?.headless ?? false;
    
    if (headless) {
      return this.getHeadlessBrowser();
    } else {
      return this.getHeadfulBrowser();
    }
  }
  
  /**
   * 获取有头浏览器实例（用于用户交互）
   */
  private static async getHeadfulBrowser(): Promise<Browser> {
    if (this.headfulBrowser && this.headfulBrowser.isConnected()) {
      return this.headfulBrowser;
    }
    
    // 防止并发初始化
    if (this.isHeadfulInitializing) {
      await new Promise(resolve => setTimeout(resolve, 1000));
      return this.getHeadfulBrowser();
    }
    
    this.isHeadfulInitializing = true;
    
    try {
      logger.info('Launching headful browser...');
      
      this.headfulBrowser = await chromium.launch({
        headless: false,
        args: [
          '--no-sandbox',
          '--disable-setuid-sandbox',
          '--disable-dev-shm-usage',
          '--disable-accelerated-2d-canvas',
          '--disable-gpu',
          '--window-size=1920,1080',
        ],
      });
      
      this.headfulBrowser.on('disconnected', () => {
        logger.warn('Headful browser disconnected');
        this.headfulBrowser = null;
      });
      
      logger.info('Headful browser launched successfully');
      return this.headfulBrowser;
    } catch (error) {
      logger.error('Failed to launch headful browser:', error);
      throw error;
    } finally {
      this.isHeadfulInitializing = false;
    }
  }
  
  /**
   * 获取无头浏览器实例（用于后台任务）
   */
  private static async getHeadlessBrowser(): Promise<Browser> {
    if (this.headlessBrowser && this.headlessBrowser.isConnected()) {
      return this.headlessBrowser;
    }
    
    // 防止并发初始化
    if (this.isHeadlessInitializing) {
      await new Promise(resolve => setTimeout(resolve, 1000));
      return this.getHeadlessBrowser();
    }
    
    this.isHeadlessInitializing = true;
    
    try {
      logger.info('Launching headless browser...');
      
      this.headlessBrowser = await chromium.launch({
        headless: true,
        args: [
          '--no-sandbox',
          '--disable-setuid-sandbox',
          '--disable-dev-shm-usage',
          '--disable-accelerated-2d-canvas',
          '--disable-gpu',
          '--window-size=1920,1080',
        ],
      });
      
      this.headlessBrowser.on('disconnected', () => {
        logger.warn('Headless browser disconnected');
        this.headlessBrowser = null;
      });
      
      logger.info('Headless browser launched successfully');
      return this.headlessBrowser;
    } catch (error) {
      logger.error('Failed to launch headless browser:', error);
      throw error;
    } finally {
      this.isHeadlessInitializing = false;
    }
  }
  
  /**
   * 关闭浏览器
   * @param options.headless 指定关闭哪种浏览器，不指定则关闭所有
   */
  static async closeBrowser(options?: BrowserOptions): Promise<void> {
    if (options?.headless === true) {
      // 只关闭无头浏览器
      if (this.headlessBrowser) {
        await this.headlessBrowser.close();
        this.headlessBrowser = null;
        logger.info('Headless browser closed');
      }
    } else if (options?.headless === false) {
      // 只关闭有头浏览器
      if (this.headfulBrowser) {
        await this.headfulBrowser.close();
        this.headfulBrowser = null;
        logger.info('Headful browser closed');
      }
    } else {
      // 关闭所有浏览器
      if (this.headfulBrowser) {
        await this.headfulBrowser.close();
        this.headfulBrowser = null;
        logger.info('Headful browser closed');
      }
      if (this.headlessBrowser) {
        await this.headlessBrowser.close();
        this.headlessBrowser = null;
        logger.info('Headless browser closed');
      }
    }
  }
  
  /**
   * 检查浏览器状态
   */
  static isConnected(options?: BrowserOptions): boolean {
    if (options?.headless === true) {
      return this.headlessBrowser?.isConnected() ?? false;
    } else if (options?.headless === false) {
      return this.headfulBrowser?.isConnected() ?? false;
    }
    // 任一浏览器连接即返回 true
    return (this.headfulBrowser?.isConnected() ?? false) || 
           (this.headlessBrowser?.isConnected() ?? false);
  }
}

// 进程退出时关闭浏览器
process.on('exit', () => {
  BrowserManager.closeBrowser();
});

process.on('SIGINT', async () => {
  await BrowserManager.closeBrowser();
  process.exit(0);
});

process.on('SIGTERM', async () => {
  await BrowserManager.closeBrowser();
  process.exit(0);
});
