/**
 * 浏览器提供商抽象基类
 * 实现通用逻辑，强制子类实现抽象方法
 */

import { IBrowserProvider } from '../interfaces/IBrowserProvider';
import {
  IBrowserCapabilities,
  ILaunchOptions,
  ILaunchResult,
  IProviderMetadata
} from '../types';

export abstract class BaseBrowserProvider implements IBrowserProvider {
  protected config: any;
  protected browser: any = null;
  protected page: any = null;

  constructor(config: any = {}) {
    this.config = config;
  }

  // ========== 抽象方法 - 子类必须实现 ==========
  abstract getName(): string;
  abstract getVersion(): string;
  abstract isFree(): boolean;
  abstract getCapabilities(): IBrowserCapabilities;
  abstract launch(options?: ILaunchOptions): Promise<ILaunchResult>;
  abstract close(): Promise<void>;
  abstract getActionFactory(): any;

  // ========== 通用实现 ==========
  
  getMetadata(): IProviderMetadata {
    return {
      name: this.getName(),
      version: this.getVersion(),
      free: this.isFree(),
      capabilities: this.getCapabilities()
    };
  }

  getBrowser(): any {
    if (!this.browser) {
      throw new Error('Browser not initialized. Call launch() first.');
    }
    return this.browser;
  }

  getPage(): any {
    if (!this.page) {
      throw new Error('Page not initialized. Call launch() first.');
    }
    return this.page;
  }

  async clearCache(): Promise<void> {
    // 默认实现，子类可覆盖
    console.warn('clearCache() not implemented for this provider');
  }

  async validateConfig(): Promise<boolean> {
    // 默认通过，子类可覆盖
    return true;
  }

  protected getConfig(): any {
    return this.config;
  }
}
