/**
 * AdsPower 指纹浏览器提供商
 * 提供 AdsPower 指纹浏览器的集成支持
 */

const BaseBrowserProvider = require('./base-provider');
const puppeteer = require('puppeteer');
const axios = require('axios');
const logger = require('../../../logger');

class AdsPowerProvider extends BaseBrowserProvider {
  constructor(config = {}) {
    super(config);
    
    this.profileId = config.profileId || process.env.ADSPOWER_USER_ID;
    this.apiBase = config.apiBase || process.env.ADSPOWER_API || 'http://local.adspower.net:50325';
    this.apiKey = config.apiKey || process.env.ADSPOWER_API_KEY;
    this.siteName = config.siteName || 'AdsPower';
    this.incognitoMode = config.incognitoMode !== false; // 默认开启无痕模式
  }

  getName() {
    return 'AdsPower';
  }

  isFree() {
    return false; // AdsPower 是付费服务
  }

  getCapabilities() {
    return {
      stealth: true,          // 支持隐身模式
      fingerprint: true,      // 支持指纹伪装
      proxy: true,            // 支持代理
      incognito: true,        // 支持无痕模式
      profiles: true,         // 支持多配置文件
      cloudflareBypass: true, // 可绕过 Cloudflare
      stripeCompatible: true  // 兼容 Stripe
    };
  }

  getVersion() {
    return '1.0.0';
  }

  async validateConfig() {
    if (!this.profileId) {
      throw new Error('未配置 AdsPower Profile ID (ADSPOWER_USER_ID)');
    }
    return true;
  }

  async launch(options = {}) {
    logger.info(this.siteName, '启动 AdsPower 指纹浏览器...');
    
    // 验证配置
    await this.validateConfig();
    
    // 构建启动URL
    const startUrl = this._buildStartUrl();
    
    // 配置请求头
    const headers = this._buildHeaders();
    
    if (this.apiKey && this.apiKey.trim()) {
      logger.info(this.siteName, '✓ 使用 API Key 认证');
    }
    
    logger.info(this.siteName, `  → 启动 AdsPower 配置: ${this.profileId}`);
    
    if (this.incognitoMode) {
      logger.info(this.siteName, `  → 无痕模式: 已启用（关闭后清除缓存）`);
    }
    
    try {
      // 调用 AdsPower API 启动浏览器
      const response = await axios.get(startUrl, { headers });
      const data = response.data;
      
      if (data.code !== 0) {
        this._handleApiError(data);
      }
      
      // 获取 WebSocket 端点
      const wsEndpoint = this._extractWsEndpoint(data);
      
      logger.info(this.siteName, `  → WebSocket: ${wsEndpoint}`);
      
      // 连接到浏览器
      this.browser = await puppeteer.connect({
        browserWSEndpoint: wsEndpoint,
        defaultViewport: options.viewport || null
      });
      
      // 获取或创建页面
      await this._setupPage();
      
      logger.success(this.siteName, '✓ ✓ AdsPower 浏览器连接成功');
      logger.info(this.siteName, '✓ 使用真实指纹，可同时绕过 Cloudflare 和 Stripe');
      
      return {
        browser: this.browser,
        page: this.page,
        wsEndpoint
      };
      
    } catch (error) {
      logger.error(this.siteName, '');
      logger.error(this.siteName, `❌ AdsPower 连接失败: ${error.message}`);
      logger.error(this.siteName, '');
      throw error;
    }
  }

  async connect(wsEndpoint) {
    logger.info(this.siteName, `连接到 AdsPower 浏览器: ${wsEndpoint}`);
    
    this.browser = await puppeteer.connect({
      browserWSEndpoint: wsEndpoint,
      defaultViewport: null
    });
    
    await this._setupPage();
    
    logger.success(this.siteName, '✓ 已连接到 AdsPower 浏览器');
    
    return {
      browser: this.browser,
      page: this.page
    };
  }

  async close() {
    if (!this.browser) {
      logger.warn(this.siteName, '浏览器未初始化，无需关闭');
      return;
    }
    
    try {
      logger.info(this.siteName, '  → 关闭浏览器...');
      
      // 关闭所有页面
      await this._closeAllPages();
      
      // 断开 Puppeteer 连接
      await this.browser.disconnect();
      logger.success(this.siteName, '  → ✓ Puppeteer 连接已断开');
      
      // 调用 AdsPower API 停止浏览器进程
      await this._stopBrowserProcess();
      
      this.browser = null;
      this.page = null;
      logger.success(this.siteName, '  → ✓ 浏览器完全关闭');
      
    } catch (error) {
      logger.error(this.siteName, `关闭浏览器失败: ${error.message}`);
      throw error;
    }
  }

  async clearCache() {
    if (!this.page) {
      logger.warn(this.siteName, '页面未初始化，跳过清除缓存');
      return;
    }
    
    logger.info(this.siteName, '  → 清除所有浏览器数据（Cookies、Cache、Storage等）...');
    
    try {
      const client = await this.page.target().createCDPSession();
      
      // 清除 Cookies
      await client.send('Network.clearBrowserCookies');
      logger.success(this.siteName, '  → ✓ 已清除所有 Cookies');
      
      // 清除缓存
      await client.send('Network.clearBrowserCache');
      logger.success(this.siteName, '  → ✓ 已清除浏览器缓存');
      
      // 清除存储
      await client.send('Storage.clearDataForOrigin', {
        origin: '*',
        storageTypes: 'all'
      });
      logger.success(this.siteName, '  → ✓ 已清除所有存储数据');
      
      // 清除页面存储
      const currentUrl = this.page.url();
      if (currentUrl && currentUrl.startsWith('http')) {
        await this.page.evaluate(() => {
          try {
            localStorage.clear();
            sessionStorage.clear();
          } catch (e) {}
        });
      }
      
      await client.detach();
      
      logger.success(this.siteName, '  → ✓ 浏览器数据清除完成（全新状态）');
      
    } catch (e) {
      logger.warn(this.siteName, `  → 清除浏览器数据失败: ${e.message}`);
    }
  }

  async newPage() {
    if (!this.browser) {
      throw new Error('浏览器未初始化');
    }
    return await this.browser.newPage();
  }

  async setUserAgent(userAgent) {
    if (!this.page) {
      throw new Error('页面未初始化');
    }
    await this.page.setUserAgent(userAgent);
  }

  async setViewport(viewport) {
    if (!this.page) {
      throw new Error('页面未初始化');
    }
    await this.page.setViewport(viewport);
  }

  // ============ 私有方法 ============

  _buildStartUrl() {
    const params = new URLSearchParams({
      user_id: this.profileId
    });
    
    // 如果启用无痕模式，添加参数
    if (this.incognitoMode) {
      params.append('clear_cache_after_closing', '1');
    }
    
    return `${this.apiBase}/api/v1/browser/start?${params.toString()}`;
  }

  _buildHeaders() {
    const headers = {};
    if (this.apiKey && this.apiKey.trim()) {
      headers['Authorization'] = `Bearer ${this.apiKey}`;
    }
    return headers;
  }

  _extractWsEndpoint(data) {
    const wsEndpoint = data.data.ws && (
      data.data.ws.puppeteer || 
      data.data.ws.selenium || 
      data.data.ws.ws || 
      data.data.ws
    );
    
    if (!wsEndpoint) {
      throw new Error('AdsPower 未返回 WebSocket 端点');
    }
    
    return wsEndpoint;
  }

  async _setupPage() {
    const pages = await this.browser.pages();
    this.page = pages[0] || await this.browser.newPage();
    
    // 关闭多余的标签页
    if (pages.length > 1) {
      for (let i = 1; i < pages.length; i++) {
        try {
          await pages[i].close();
        } catch (e) {
          // 忽略关闭失败
        }
      }
    }
  }

  async _closeAllPages() {
    try {
      const pages = await this.browser.pages();
      logger.info(this.siteName, `  → 关闭所有标签页 (共 ${pages.length} 个)...`);
      
      for (const page of pages) {
        try {
          await page.close();
          logger.info(this.siteName, `  → ✓ 已关闭一个标签页`);
        } catch (e) {
          logger.warn(this.siteName, `  → 关闭标签页失败: ${e.message}`);
        }
      }
    } catch (e) {
      logger.warn(this.siteName, `  → 获取页面列表失败: ${e.message}`);
    }
  }

  async _stopBrowserProcess() {
    if (!this.profileId) return;
    
    const stopUrl = `${this.apiBase}/api/v1/browser/stop?user_id=${encodeURIComponent(this.profileId)}`;
    const headers = this._buildHeaders();
    
    logger.info(this.siteName, `  → 调用 AdsPower API 停止浏览器进程...`);
    
    try {
      const response = await axios.get(stopUrl, { headers });
      const data = response.data;
      
      if (data.code === 0) {
        logger.success(this.siteName, '  → ✓ AdsPower 浏览器进程已停止');
      } else {
        logger.warn(this.siteName, `  → AdsPower stop API 返回: ${data.msg || JSON.stringify(data)}`);
      }
    } catch (e) {
      logger.warn(this.siteName, `  → 调用 AdsPower stop API 失败: ${e.message}`);
      logger.info(this.siteName, '  → 浏览器可能已经关闭，或需要手动关闭');
    }
  }

  _handleApiError(data) {
    logger.error(this.siteName, '');
    logger.error(this.siteName, `AdsPower API 返回错误: ${JSON.stringify(data)}`);
    logger.error(this.siteName, '');
    logger.error(this.siteName, '解决方案：');
    logger.error(this.siteName, '1. 确保 AdsPower 应用已启动并登录');
    logger.error(this.siteName, `2. 检查配置文件 ID 是否正确: ${this.profileId}`);
    logger.error(this.siteName, '3. 如果需要 API Key，请在 AdsPower 设置中生成');
    logger.error(this.siteName, '4. 尝试在 AdsPower 中手动打开一次浏览器配置');
    logger.error(this.siteName, '');
    throw new Error(`AdsPower 启动失败: ${data.msg || JSON.stringify(data)}`);
  }
}

module.exports = AdsPowerProvider;
